🌍 Networking

QUIC

QUIC

A UDP-based transport protocol. Reduces connection setup latency.

📖 Detailed Explanation

QUIC (Quick UDP Internet Connections) is a next-generation transport protocol developed by Google in 2012 and standardized as IETF RFC 9000 in 2021. It implements the functions of TCP+TLS+HTTP/2 as a single protocol on top of UDP, fundamentally resolving the connection setup latency and Head-of-Line Blocking problems of conventional web communication. Adopted as the foundation protocol of HTTP/3, it currently handles more than 25% of global web traffic.

QUIC's core innovation is 0-RTT (Zero Round Trip Time) connection setup. Conventional TCP+TLS 1.3 requires at least 2-RTT (about 200-300ms), but QUIC can send encrypted data from the first packet to a server it has connected to before, which greatly improves perceived speed. Even new connections are completed in just 1-RTT, which is especially advantageous in mobile environments.

Multiplexing and connection migration are other strengths of QUIC. In TCP, the loss of a single packet blocks the entire stream, but QUIC multiplexes over independent streams, so the loss of a particular stream does not affect other streams. In addition, because it operates based on a Connection ID, the connection is maintained without being dropped even when switching from Wi-Fi to LTE.

In terms of security, QUIC has TLS 1.3 built into the protocol itself, encrypting not only all payloads but also most of the headers. This prevents man-in-the-middle attacks and protocol ossification. Major companies such as Google, Facebook, Cloudflare, and Akamai have already adopted QUIC, and it is supported by all major browsers, including Chrome, Firefox, and Safari.

💻 Code Example

import asyncio
from aioquic.asyncio import connect, serve
from aioquic.asyncio.protocol import QuicConnectionProtocol
from aioquic.quic.configuration import QuicConfiguration

# QUIC 클라이언트 예제 (aioquic 라이브러리)
async def quic_client():
    configuration = QuicConfiguration(
        is_client=True,
        alpn_protocols=["h3"],  # HTTP/3 프로토콜
    )
    # 인증서 검증 비활성화 (테스트용)
    configuration.verify_mode = False

    async with connect(
        "localhost",
        4433,
        configuration=configuration,
    ) as protocol:
        # 스트림 생성 및 데이터 전송
        stream_id = protocol._quic.get_next_available_stream_id()
        protocol._quic.send_stream_data(
            stream_id,
            b"GET / HTTP/3\r\n\r\n",
            end_stream=True
        )

        # 응답 대기
        await asyncio.sleep(1)
        print("QUIC 연결 성공!")

# HTTP/3 클라이언트 (httpx + h3)
import httpx

async def http3_request():
    # httpx는 HTTP/3 지원 (h3 백엔드 필요)
    async with httpx.AsyncClient(http2=True) as client:
        response = await client.get("https://cloudflare-quic.com")
        print(f"Protocol: {response.http_version}")
        print(f"Status: {response.status_code}")

# QUIC 연결 상태 확인
def check_quic_support(url):
    """서버의 QUIC/HTTP3 지원 여부 확인"""
    import subprocess
    result = subprocess.run(
        ["curl", "-I", "--http3", url],
        capture_output=True, text=True
    )
    return "HTTP/3" in result.stdout

asyncio.run(quic_client())
package main

import (
    "context"
    "crypto/tls"
    "fmt"
    "io"
    "log"
    "net/http"

    "github.com/quic-go/quic-go"
    "github.com/quic-go/quic-go/http3"
)

// HTTP/3 클라이언트 (quic-go 라이브러리)
func main() {
    // HTTP/3 RoundTripper 설정
    roundTripper := &http3.RoundTripper{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: false,
        },
        QuicConfig: &quic.Config{
            MaxIdleTimeout:  30 * time.Second,
            EnableDatagrams: true,
        },
    }
    defer roundTripper.Close()

    client := &http.Client{
        Transport: roundTripper,
    }

    // HTTP/3 요청
    resp, err := client.Get("https://cloudflare-quic.com")
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    fmt.Printf("Protocol: %s\n", resp.Proto) // HTTP/3.0
    fmt.Printf("Status: %s\n", resp.Status)

    body, _ := io.ReadAll(resp.Body)
    fmt.Printf("Body: %s\n", string(body[:100]))
}

// QUIC 서버 예제
func startQUICServer() {
    // TLS 인증서 로드
    certFile := "server.crt"
    keyFile := "server.key"

    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Alt-Svc", `h3=":443"; ma=86400`)
        fmt.Fprintf(w, "Hello from HTTP/3!")
    })

    // HTTP/3 서버 시작
    err := http3.ListenAndServeQUIC(
        ":443",
        certFile,
        keyFile,
        handler,
    )
    if err != nil {
        log.Fatal(err)
    }
}
// Node.js QUIC 지원 (실험적 - Node.js 15+)
// --experimental-quic 플래그 필요

const { createQuicSocket } = require('net');

// QUIC 클라이언트
async function quicClient() {
    const socket = createQuicSocket({ client: {} });

    const session = await socket.connect({
        address: 'localhost',
        port: 4433,
        alpn: 'h3',
        servername: 'localhost'
    });

    session.on('secure', () => {
        console.log('QUIC 연결 성공!');
        console.log('Protocol:', session.alpnProtocol);
        console.log('Cipher:', session.cipher.name);

        // 스트림 생성
        const stream = session.openStream({ halfOpen: true });
        stream.write('GET / HTTP/3\r\n\r\n');
        stream.end();

        stream.on('data', (data) => {
            console.log('응답:', data.toString());
        });
    });

    session.on('close', () => {
        console.log('연결 종료');
        socket.close();
    });
}

// HTTP/3 fetch (브라우저에서 자동 지원)
// 브라우저는 Alt-Svc 헤더를 통해 자동으로 HTTP/3 사용

// Nginx QUIC 설정 예제 (nginx.conf)
const nginxQuicConfig = `
server {
    listen 443 quic reuseport;  # QUIC (UDP)
    listen 443 ssl;              # HTTPS (TCP)

    http2 on;
    http3 on;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    # TLS 1.3 필수 (QUIC 요구사항)
    ssl_protocols TLSv1.3;

    # Alt-Svc 헤더로 HTTP/3 지원 알림
    add_header Alt-Svc 'h3=":443"; ma=86400';

    # 0-RTT 활성화 (Early Data)
    ssl_early_data on;

    location / {
        root /var/www/html;
    }
}
`;

// QUIC 연결 상태 확인 (curl)
// curl --http3 -I https://cloudflare-quic.com
// curl --http3-only https://example.com

console.log('QUIC/HTTP3 설정 예제');
quicClient().catch(console.error);

🗣️ Say It Like This in Practice

💬 In a Performance Optimization Meeting
"Mobile users' TTFB is 400ms, but if we adopt QUIC, we can send data from the very first request with 0-RTT, which can cut more than 200ms. If we enable HTTP/3 on Cloudflare or AWS CloudFront, we can apply it right away without modifying the server."
💬 In a technical interview
"QUIC is a protocol that integrates TCP's reliability, TLS's security, and HTTP/2's multiplexing on top of UDP. It solves TCP's HOL Blocking problem, and with Connection ID-based operation, the connection is maintained even when the network switches. Especially in mobile environments with a lot of packet loss, it shows a performance improvement of more than 30% compared to TCP."
💬 In an Infrastructure Design Discussion
"When adopting QUIC, you need to open UDP port 443 on the firewall. Because some corporate networks block UDP, you should announce HTTP/3 support with the Alt-Svc header and make clients automatically fall back to TCP when a QUIC connection fails."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
UDP port not opened

QUIC uses UDP port 443. If you open only TCP 443 in the firewall or security group and block UDP, QUIC connections will fail. Be sure to allow inbound UDP 443 in AWS Security Group and GCP Firewall.

❌
Ignoring 0-RTT security risks

0-RTT Early Data is vulnerable to replay attacks. For non-idempotent requests such as payments and orders, you should disable 0-RTT or implement duplicate request detection logic on the server.

❌
Missing load balancer configuration

QUIC's Connection ID is generated by the client. If you do not configure Connection ID-based session persistence instead of IP hashing on the L4 load balancer, connection migration will not work properly.

✅
How to Adopt QUIC Correctly

Adopt it first through a CDN (Cloudflare, Fastly), and migrate gradually with the Alt-Svc header. Maintain TCP fallback, and after comparing QUIC vs TCP performance through monitoring, consider applying it directly to the origin server.

🔗 Related Terms

📚 Learn More