Mô hình mạng & Các tầngNetwork Models & Layers
Thuộc bộ kiến thức Network Engineer Roadmap.
Tổng quan
Network model (mô hình mạng) là một framework tham chiếu phân tầng, chia bài toán khổng lồ “đưa dữ liệu từ một chương trình trên máy này tới một chương trình trên máy khác, ở bất kỳ đâu trên Trái Đất” thành một chồng (stack) các tầng nhỏ hơn, có định nghĩa rõ ràng. Mỗi tầng (layer) chỉ có một trách nhiệm duy nhất, chỉ giao tiếp với tầng ngay trên và ngay dưới nó, và có thể được thiết kế, cài đặt cũng như suy luận một cách độc lập.
Có hai mô hình thống trị lĩnh vực này:
- OSI model (Open Systems Interconnection) — mô hình tham chiếu khái niệm gồm 7 tầng do ISO công bố. Không ai triển khai một “OSI stack” thực sự, nhưng mọi kỹ sư đều dùng từ vựng của nó hằng ngày (“đây là vấn đề ở Layer 2”, “ta cần một L7 load balancer”).
- TCP/IP model (còn gọi là Internet model) — mô hình thực tế gồm 4 hoặc 5 tầng, mô tả cách Internet thật sự hoạt động. Đây chính là stack đang chạy trong hệ điều hành của bạn ngay lúc này.
Tại sao lại cần phân tầng?
- Separation of concerns (tách bạch trách nhiệm) — Ethernet không cần biết gì về HTTP; TCP không cần biết nó đang chạy trên Wi-Fi hay cáp quang.
- Interoperability (khả năng tương tác) — miễn là hai thiết bị đồng ý về protocol tại một tầng nhất định, các tầng bên dưới có thể hoàn toàn khác nhau.
- Fault isolation (khoanh vùng lỗi) — khi có sự cố, việc phân tầng cho bạn một “chiếc thang” có hệ thống để leo: cáp có kết nối không (L1)? Switch có forward frame không (L2)? Có route được tới đích không (L3)? Port có mở không (L4)? Ứng dụng có phản hồi không (L7)?
Note này chính là bản đồ tư duy mà phần còn lại của roadmap dựa vào. Một khi bạn có thể đặt bất kỳ protocol, thiết bị hay lỗi nào vào đúng tầng của nó, mọi thứ còn lại — core protocols, network devices, và IP addressing & subnetting — sẽ tự khớp vào chỗ.
Kiến thức nền tảng
Mô hình OSI 7 tầng
Câu ghi nhớ kinh điển (từ trên xuống) là “All People Seem To Need Data Processing” (Application → Physical), hoặc từ dưới lên “Please Do Not Throw Sausage Pizza Away”.
Mỗi tầng trao đổi một PDU (Protocol Data Unit) với tầng ngang hàng (peer) trên host phía xa. Tên của PDU thay đổi khi bạn đi xuống stack — cần nhớ kỹ cách gọi tên này vì kỹ sư dùng nó liên tục.
| # | Tầng (Layer) | PDU | Chức năng cốt lõi | Ví dụ protocol / chuẩn | Ví dụ thiết bị | Lỗi thường gặp |
|---|---|---|---|---|---|---|
| 7 | Application | Data | Giao diện tới ứng dụng người dùng; định nghĩa ngữ nghĩa của việc trao đổi | HTTP, HTTPS, DNS, SMTP, FTP, SSH, gRPC | Firewall (L7/WAF), API gateway, proxy | Lỗi 404/500, bad request, cert hết hạn, sai Host header |
| 6 | Presentation | Data | Chuyển đổi, encoding, serialization, mã hóa, nén | TLS/SSL, JPEG, ASCII/UTF-8, JSON/Protobuf, gzip | (thường là thư viện phần mềm) | Sai encoding, TLS handshake thất bại, hỏng charset |
| 5 | Session | Data | Thiết lập, quản lý, đóng session/dialog giữa các ứng dụng | NetBIOS, RPC, SOCKS, (TLS session resumption) | (phần mềm) | Session timeout, session half-open, auth token hết hạn |
| 4 | Transport | Segment (TCP) / Datagram (UDP) | Giao nhận end-to-end, ports/multiplexing, độ tin cậy, flow & congestion control | TCP, UDP, QUIC (trên UDP), SCTP | L4 load balancer, stateful firewall, NAT | Port đóng/bị filter, connection refused/reset, retransmit, vấn đề MTU/MSS |
| 3 | Network | Packet | Địa chỉ logic và routing giữa các mạng | IP (IPv4/IPv6), ICMP, IPsec, OSPF, BGP | Router, L3 switch, firewall | No route to host, TTL exceeded, sai subnet/gateway, routing loop |
| 2 | Data Link | Frame | Giao nhận node-to-node trên cùng một link; địa chỉ MAC; phát hiện lỗi | Ethernet, Wi-Fi (802.11), PPP, ARP, VLAN (802.1Q), STP | Switch, bridge, NIC, wireless AP | MAC flapping, sai VLAN, duplex mismatch, lỗi CRC, STP loop |
| 1 | Physical | Bit (symbol) | Truyền các bit thô qua môi trường; điện áp, ánh sáng, sóng radio, sơ đồ chân | Ethernet PHY, RJ45, fiber, DSL, USB, Bluetooth radio | Cáp, hub, repeater, transceiver, modem | Đứt cáp, không có link light, hỏng SFP, nhiễu EMI, sai pinout, port down |
Một cách nhớ tiện: các tầng 1–4 là các tầng “thấp”/hạ tầng (đưa các bit tới đúng port trên đúng host một cách tin cậy), còn các tầng 5–7 là các tầng “cao”/ứng dụng (làm cho dữ liệu có ý nghĩa với phần mềm). Network engineer chủ yếu sống ở L1–L4; developer chủ yếu sống ở L5–L7.
Lưu ý về các tầng “phụ”. Trong thực tế, các tầng 5, 6 và 7 khá mờ nhòe — cùng một protocol (ví dụ HTTPS) trải cả presentation (TLS) lẫn application (HTTP) cùng lúc. Đây là một lý do khiến mô hình TCP/IP gộp chúng lại.
Mô hình TCP/IP và cách nó ánh xạ sang OSI
Mô hình TCP/IP là thứ Internet thật sự triển khai (các tầng của nó được định nghĩa trong RFC 1122). Nó có hai cách mô tả phổ biến — bản 4 tầng và bản 5 tầng (tách tầng dưới cùng ra, khớp với OSI hơn). Cả hai đều đúng; bản 5 tầng dễ dạy hơn vì nó tách phần cáp (Physical) khỏi phần đóng frame (Data Link).
| TCP/IP (4 tầng) | TCP/IP (5 tầng) | Tương đương OSI | Ví dụ protocol |
|---|---|---|---|
| Application | Application | 7 + 6 + 5 (App, Presentation, Session) | HTTP, DNS, TLS, SSH, SMTP |
| Transport | Transport | 4 (Transport) | TCP, UDP, QUIC |
| Internet | Internet (Network) | 3 (Network) | IP, ICMP, IPsec |
| Link / Network Access | Data Link | 2 (Data Link) | Ethernet, ARP, Wi-Fi |
| Physical | 1 (Physical) | Cáp, radio, fiber |
Vì sao stack thực tế là TCP/IP chứ không phải OSI:
- Nó đã được triển khai, và đã thắng. TCP/IP được cài đặt, deploy và cải tiến trên ARPANET/Internet trong khi OSI vẫn còn là một đặc tả trên bàn hội đồng. Code chạy được đã đánh bại một mô hình hoàn hảo.
- Nó thực dụng. Các mối quan tâm về session và presentation không cần một tầng mạng riêng — chúng được xử lý bởi các thư viện ở tầng application (một thư viện TLS, một bộ serialize JSON), nên gộp chúng lại đơn giản hơn.
- “Eo thắt hẹp” (narrow waist). Cái hay của TCP/IP là IP đóng vai một Layer 3 tối giản, phổ quát: bất kỳ công nghệ link nào bên dưới (Ethernet, Wi-Fi, 5G, vệ tinh) và bất kỳ ứng dụng nào bên trên (web, email, video) đều tương tác được miễn là chúng nói IP ở giữa. Hình dạng “đồng hồ cát” này là lý do Internet mở rộng quy mô được.
Vậy: dùng OSI để có từ vựng và để troubleshoot; hiểu rằng các bit trên dây tuân theo mô hình TCP/IP.
Encapsulation và decapsulation
Dữ liệu không “dịch chuyển tức thời” xuống stack — mỗi tầng bọc (wrap) PDU từ tầng trên bằng header của riêng nó (và đôi khi cả trailer), thêm vào thông tin điều khiển mà tầng ngang hàng cần. Việc bọc này là encapsulation khi đi xuống (gửi), và decapsulation — gỡ từng header — khi đi lên (nhận). Đây là khái niệm cơ học quan trọng nhất trong networking.
Gửi (trên → dưới, encapsulation):
Application: [ Data ] (ví dụ một HTTP request)
Transport: [ TCP hdr | Data ] → SEGMENT (thêm src/dst port, seq#, flags)
Network: [ IP hdr | TCP hdr | Data ] → PACKET (thêm địa chỉ IP src/dst, TTL)
Data Link: [ Eth hdr | IP hdr | TCP hdr | Data | Eth trailer ] → FRAME (thêm MAC src/dst, FCS/CRC)
Physical: 0101110010101110... → BITS (mã hóa thành tín hiệu điện/quang/radio)
- Tầng Transport cắt dữ liệu ứng dụng thành các mảnh vừa với mạng (theo MSS, Maximum Segment Size) và thêm header TCP hoặc UDP → segment (TCP) / datagram (UDP).
- Tầng Network thêm IP header (địa chỉ IP nguồn và đích, TTL, protocol number) → packet (còn gọi là IP datagram).
- Tầng Data Link thêm header (địa chỉ MAC nguồn/đích) và trailer (checksum FCS/CRC để phát hiện lỗi) → frame.
- Tầng Physical chuyển các byte của frame thành bits — tín hiệu thật trên dây đồng, cáp quang, hoặc không khí.
Nhận (dưới → trên, decapsulation): ngược lại y hệt. NIC biến tín hiệu về lại thành frame, kiểm tra FCS, gỡ Ethernet header/trailer → đẩy packet lên. Tầng IP kiểm tra IP đích và gỡ IP header → đẩy segment lên. TCP kiểm tra port, ráp lại/sắp xếp lại, gỡ header của nó → giao dữ liệu cho ứng dụng đang lắng nghe trên port đó.
Những mô hình tư duy quan trọng mà điều này mở ra:
- Mỗi tầng chỉ đọc header của chính nó. Một switch (L2) đọc Ethernet header và bỏ qua IP payload; một router (L3) đọc IP header và ghi lại Ethernet header cho hop kế tiếp; một firewall có thể được xây để soi bất kỳ tầng nào bạn muốn.
- Địa chỉ MAC đổi ở mỗi hop; địa chỉ IP (thường) thì không. Khi một packet đi qua các router, frame L2 bị gỡ và dựng lại cho từng link (MAC nguồn/đích mới), trong khi địa chỉ IP L3 giữ nguyên end-to-end. Đây là cái insight kinh điển hay hỏi khi phỏng vấn.
- Overhead là có thật. Header của mỗi tầng ăn vào payload. Đây là lý do MTU (kích thước frame tối đa, kinh điển là 1500 byte với Ethernet) và MSS quan trọng, và vì sao các vấn đề fragmentation hay PMTUD gây ra những bug khó hiểu kiểu “request lớn thì bị treo”.
Nhìn kỹ tầng Transport: TCP vs UDP
Layer 4 là nơi “các mạng” trở thành “các kết nối giữa các chương trình”. Có hai protocol thống trị.
TCP (Transmission Control Protocol) — connection-oriented, tin cậy, có thứ tự, dạng byte-stream.
- 3-way handshake để thiết lập kết nối:
- Client → Server:
SYN(seq = x) — “mình muốn nói chuyện, sequence number khởi đầu của mình là x” - Server → Client:
SYN, ACK(seq = y, ack = x+1) — “ok, của mình là y; mình đã nhận được của bạn” - Client → Server:
ACK(ack = y+1) — “nhận rồi, ta đã kết nối” Sau bước này, cả hai phía đã thống nhất sequence number và kết nối ở trạng thái ESTABLISHED.
- Client → Server:
- Reliability (độ tin cậy) — mỗi byte đều được đánh số thứ tự; bên nhận ACK những gì đã nhận; dữ liệu chưa được ACK sẽ được retransmit (truyền lại) sau timeout (RTO) hoặc khi có duplicate ACK (fast retransmit).
- Ordering (thứ tự) — các segment mang sequence number, nên nếu tới không đúng thứ tự vẫn được ráp lại đúng trước khi giao cho app.
- Flow control — cơ chế sliding window (window size được quảng bá) cho phép bên nhận nói với bên gửi “tôi chỉ buffer được từng này thôi”, tránh việc bên gửi nhanh làm ngợp bên nhận chậm.
- Congestion control — các thuật toán (slow start, congestion avoidance, ví dụ CUBIC/Reno/BBR) điều tiết bên gửi dựa trên mức độ nghẽn của mạng (mất gói / độ trễ), bảo vệ Internet khỏi sụp đổ.
- Teardown (đóng kết nối) — đóng “lịch sự” dùng
FIN/FIN, ACKở mỗi chiều (trao đổi 4 bước). Ngắt đột ngột dùngRST(reset) — “kết nối này mất rồi, đừng nói nữa”. MộtRSTtrong bản capture gần như luôn báo hiệu vấn đề: port đóng, firewall drop, app crash, hoặc timeout.
UDP (User Datagram Protocol) — connectionless, không tin cậy, dạng message. Chỉ có port nguồn/đích, độ dài, và một checksum. Không handshake, không ACK, không sắp thứ tự, không congestion control. Nó là một lớp bọc mỏng trên IP: “fire and forget” (bắn rồi quên). Nếu cần độ tin cậy, bạn tự xây bên trên (đó chính xác là điều QUIC làm trên UDP).
| Thuộc tính | TCP | UDP |
|---|---|---|
| Kết nối | Connection-oriented (có handshake) | Connectionless |
| Độ tin cậy | Đảm bảo giao nhận (ACK + retransmit) | Best-effort, không đảm bảo |
| Thứ tự | Giao đúng thứ tự | Không sắp thứ tự |
| Flow / congestion control | Có | Không |
| Kích thước header | 20+ byte | 8 byte |
| Tốc độ / độ trễ | Độ trễ cao hơn (setup + ACK) | Độ trễ thấp hơn, ít overhead |
| Tên PDU | Segment | Datagram |
| Broadcast/multicast | Không | Có |
| Dùng điển hình | HTTP(S), SSH, SMTP, kết nối DB, truyền file | DNS, DHCP, VoIP, video streaming, game, QUIC/HTTP-3 |
Nguyên tắc chung: dùng TCP khi độ chính xác quan trọng hơn tốc độ (tải một trang web, truyền một file, một truy vấn database — mất một byte là không chấp nhận được). Dùng UDP khi tính kịp thời quan trọng hơn sự hoàn hảo và bạn có thể chịu/tự xử lý việc mất gói (một gói thoại bị rớt còn hơn là bị trễ; một bản cập nhật trạng thái game bị rớt sẽ được bản kế tiếp thay thế). Lưu ý web hiện đại đang chuyển sang QUIC/HTTP-3, chạy các stream tin cậy, có thứ tự trên UDP để có được đảm bảo của TCP mà không bị head-of-line blocking và handshake chậm.
Khái niệm chính
Nói chuyện theo tầng: “L2 vs L3”, “L4 vs L7”
Lợi ích thực tế lớn nhất của các mô hình này là một bộ từ vựng chung để mô tả một thiết bị hay một quyết định vận hành ở đâu.
Thiết bị L2 vs L3 (xem network devices):
- Một switch về bản chất là thiết bị L2 — nó forward frame dựa trên địa chỉ MAC, trong một broadcast domain / LAN duy nhất. Nó không biết và không quan tâm tới IP.
- Một router là thiết bị L3 — nó forward packet giữa các mạng khác nhau dựa trên địa chỉ IP và một routing table.
- Một “Layer 3 switch” là switch có tích hợp sẵn phần cứng routing — nó làm được cả hai (switching L2 nhanh trong các VLAN và routing L3 giữa chúng).
Middlebox L4 vs L7 — sự phân biệt này thống trị hạ tầng hiện đại:
| L4 (Transport) load balancer / firewall | L7 (Application) load balancer / firewall | |
|---|---|---|
| Nhìn thấy | Địa chỉ IP + port TCP/UDP | Toàn bộ dữ liệu ứng dụng (URL, header, cookie, HTTP method) |
| Ra quyết định dựa trên | 5-tuple (src/dst IP, src/dst port, protocol) | Hostname, path, header, cookie, nội dung request |
| Ví dụ | AWS NLB, HAProxy ở chế độ TCP, iptables, IPVS | AWS ALB, Nginx/Envoy, API gateway, WAF |
| Chi phí | Nhanh, rẻ, không phụ thuộc protocol | Tốn CPU hơn (phải parse & thường phải terminate TLS) |
| Có thể làm | Route “toàn bộ traffic trên :443 tới pool này" | "Route /api/* chỗ này, /images/* chỗ kia; chặn mẫu SQL-injection” |
Một firewall L4 quyết định “cho phép/từ chối dựa trên IP + port” (stateful firewall kinh điển). Một firewall L7 / WAF hiểu protocol ứng dụng và có thể chặn, ví dụ, một HTTP request độc hại dù port đang mở hợp lệ.
Khoanh vùng lỗi theo tầng (chiếc thang troubleshooting)
Vì stack được phân tầng, cách debug chuyên nghiệp là cô lập tầng đang hỏng từ dưới lên (hoặc dùng chia-để-trị). Một checklist kinh điển:
| Tầng | Câu hỏi | Công cụ / bằng chứng |
|---|---|---|
| L1 Physical | Có link không? Cáp/SFP có tốt không? | Link LED, ethtool, interface counters (CRC/error), đổi cáp |
| L2 Data Link | Đúng VLAN chưa? MAC đã học chưa? ARP có phân giải không? | arp -a, MAC table của switch, ip neigh, kiểm tra VLAN tag |
| L3 Network | Có tới được IP không? Route/gateway đúng chưa? | ping, traceroute/tracert, ip route, kiểm tra subnet mask |
| L4 Transport | Port có mở/listening/tới được không? | telnet host port, nc -zv, ss -tlnp, tìm RST/SYN retransmit |
| L5–L7 App | App có trả lời đúng không? TLS ổn không? | curl -v, openssl s_client, log app, HTTP status code |
Kỷ luật ở đây: đừng debug app (L7) khi cáp đang bị rút (L1). Câu đùa “It’s always DNS” tồn tại chính vì kỹ sư hay nhảy cóc qua các tầng. ping chạy nhưng curl lỗi → L3 ổn, hãy nhìn L4/L7. ping bằng IP mà không tới nhưng interface đang up → nhìn L2/L3 (routing, ARP, gateway).
Các tầng cao trong thực tế: session, presentation, application
Trong thế giới TCP/IP, ba tầng OSI này bị gộp thành “Application”, nhưng các mối quan tâm thì vẫn có thật và đáng gọi tên:
- Session (L5) — theo dõi một cuộc hội thoại logic kéo dài hơn một request đơn lẻ. Trong thực tế: session web (một session cookie / JWT gắn nhiều HTTP request stateless vào một người dùng đã đăng nhập), TLS session resumption (tránh handshake đầy đủ khi kết nối lại), session kết nối database, và các kênh RPC. Lỗi thường thấy: “tôi bị đăng xuất”, “token hết hạn”, “kết nối rớt giữa chừng”.
- Presentation (L6) — cách dữ liệu được biểu diễn để cả hai phía đồng ý về ý nghĩa của nó: character encoding (UTF-8 vs Latin-1 → bug mojibake), serialization (JSON, Protobuf, XML, MessagePack), compression (gzip, Brotli), và quan trọng nhất là encryption: TLS là dịch vụ tầng presentation kinh điển, biến một byte stream plaintext thành một luồng được xác thực và mã hóa. TLS handshake (thương lượng cipher suite, trao đổi certificate) là mối quan tâm tầng presentation, đặt trên một kết nối TCP (transport).
- Application (L7) — protocol mà phần mềm thật sự nói: HTTP/HTTPS cho web và API, DNS cho phân giải tên, SMTP/IMAP cho email, SSH cho remote shell, gRPC cho giao tiếp service-to-service. Đây là nơi “request” và “response” mà developer suy luận thật sự sống. Đào sâu về những cái này thuộc về core protocols.
Một ví dụ cụ thể gắn kết mọi thứ lại — tải https://example.com:
- DNS (L7, trên UDP/L4) phân giải
example.com→ một IP. - TCP (L4) 3-way handshake tới IP của server trên port 443.
- TLS (L6) handshake thương lượng mã hóa và xác thực certificate.
- HTTP (L7) request/response chảy bên trong đường hầm TLS đã mã hóa.
- Bên dưới tất cả, mọi byte đã được encapsulate thành TCP segment → IP packet → Ethernet/Wi-Fi frame → bits, được các router (L3) định tuyến từng hop và các switch (L2) chuyển mạch từng link.
Chỉ một URL đó đã vận dụng toàn bộ stack — và đó chính xác là lý do mô hình phân tầng là nền tảng mà mọi thứ khác xây lên trên.
Best Practices
- Học OSI để có từ vựng, học TCP/IP để hiểu thực tế. Khi troubleshoot hay phỏng vấn, hãy gọi tên tầng một cách rõ ràng (“đây là vấn đề L2”) — điều đó buộc bạn phải chính xác và giúp giao tiếp nhanh hơn.
- Debug từ dưới lên (hoặc chia-để-trị), đừng đoán mò. Xác nhận L1/L2 trước khi đổ lỗi cho app. Dùng chiếc thang troubleshooting ở trên để không bao giờ nhảy cóc qua một tầng.
- Nhớ tên các PDU và cái gì thay đổi ở mỗi hop. “Segment → packet → frame → bits”, và “MAC đổi mỗi hop, IP giữ nguyên end-to-end” là hai sự thật mở khóa hầu hết câu hỏi về encapsulation.
- Chọn đúng transport cho việc cần làm. Mặc định dùng TCP cho các luồng cần độ chính xác; chọn UDP (hoặc QUIC) cho traffic nhạy về độ trễ, chịu được mất gói, hoặc fanout cao (broadcast/multicast) — và đừng tự phát minh lại reliability trên UDP trừ khi thật sự cần.
- Chọn middlebox L4 vs L7 một cách có chủ đích. Dùng LB/firewall L4 cho throughput thô và routing không phụ thuộc protocol; dùng L7 (ALB, Nginx, Envoy, WAF) khi cần routing theo nội dung, terminate TLS, hoặc bảo mật hiểu-ứng-dụng — và chấp nhận cái giá về CPU.
- Để ý MTU/MSS. Overhead của encapsulation và MTU không khớp (VPN, tunnel, jumbo frame) gây fragmentation và bug PMTUD black-hole; hãy clamp MSS trên tunnel và giữ path MTU nhất quán.
- Terminate và soi ở đúng tầng. Đừng bắt một thiết bị L4 làm content filtering, và đừng đốt CPU L7 cho traffic mà chỉ cần forward ở L4.
- Capture traffic để nhìn thấy các tầng.
tcpdump/Wireshark cho bạn thấy từng header (Ethernet → IP → TCP → payload) một cách trực quan. Đọc một bản capture là cách nhanh nhất để thấm khái niệm encapsulation và để phát hiện vấn đềRST/retransmit/handshake.
Tài liệu tham khảo
- OSI Model — Cloudflare Learning Center
- What is the OSI Model? — Cisco
- RFC 1122 — Requirements for Internet Hosts (Communication Layers)
- RFC 9293 — Transmission Control Protocol (TCP)
- RFC 768 — User Datagram Protocol (UDP)
- TCP vs UDP — Cloudflare Learning Center
- What is the Internet Protocol (IP)? — Cloudflare
- TCP/IP Model — MDN / IBM overview
Part of the Network Engineer Roadmap knowledge base.
Overview
A network model is a layered reference framework that breaks the enormous problem of “get data from one program on one machine to another program on another machine, anywhere on Earth” into a stack of smaller, well-defined layers. Each layer has a single responsibility, talks only to the layers directly above and below it, and can be designed, implemented, and reasoned about independently.
Two models dominate the field:
- The OSI model (Open Systems Interconnection) — a 7-layer conceptual reference model published by ISO. Nobody ships an “OSI stack”, but every engineer uses its vocabulary daily (“that’s a Layer 2 problem”, “we need an L7 load balancer”).
- The TCP/IP model (also called the Internet model) — a 4- or 5-layer practical model that describes how the actual Internet works. This is the stack running in your operating system right now.
Why bother with layering at all?
- Separation of concerns — Ethernet doesn’t need to know about HTTP; TCP doesn’t need to know whether it’s running over Wi-Fi or fiber.
- Interoperability — as long as two devices agree on the protocol at a given layer, the layers below can differ completely.
- Fault isolation — when something breaks, layering gives you a systematic ladder to climb: is the cable up (L1)? Is the switch forwarding (L2)? Can I route to the destination (L3)? Is the port open (L4)? Is the app responding (L7)?
This note is the mental map the rest of the roadmap hangs off. Once you can place any protocol, device, or failure on the correct layer, everything else — core protocols, network devices, and IP addressing & subnetting — clicks into place.
Fundamentals
The OSI 7-layer model
The classic mnemonic (top to bottom) is “All People Seem To Need Data Processing” (Application → Physical), or bottom to top “Please Do Not Throw Sausage Pizza Away”.
Each layer exchanges a PDU (Protocol Data Unit) with its peer layer on the remote host. The PDU name changes as you move down the stack — this naming is worth memorizing because engineers use it constantly.
| # | Layer | PDU | Core function | Example protocols / standards | Example devices | Typical failures |
|---|---|---|---|---|---|---|
| 7 | Application | Data | Interface to the end-user application; defines the semantics of the exchange | HTTP, HTTPS, DNS, SMTP, FTP, SSH, gRPC | Firewalls (L7/WAF), API gateways, proxies | 404/500 errors, bad request, expired cert, wrong Host header |
| 6 | Presentation | Data | Translation, encoding, serialization, encryption, compression | TLS/SSL, JPEG, ASCII/UTF-8, JSON/Protobuf, gzip | (usually software libraries) | Encoding mismatch, TLS handshake failure, charset corruption |
| 5 | Session | Data | Establishes, manages, and tears down sessions/dialogs between apps | NetBIOS, RPC, SOCKS, (TLS session resumption) | (software) | Session timeout, half-open sessions, auth token expiry |
| 4 | Transport | Segment (TCP) / Datagram (UDP) | End-to-end delivery, ports/multiplexing, reliability, flow & congestion control | TCP, UDP, QUIC (over UDP), SCTP | L4 load balancers, stateful firewalls, NAT | Port closed/filtered, connection refused/reset, retransmits, MTU/MSS issues |
| 3 | Network | Packet | Logical addressing and routing between networks | IP (IPv4/IPv6), ICMP, IPsec, OSPF, BGP | Routers, L3 switches, firewalls | No route to host, TTL exceeded, wrong subnet/gateway, routing loops |
| 2 | Data Link | Frame | Node-to-node delivery on the same link; MAC addressing; error detection | Ethernet, Wi-Fi (802.11), PPP, ARP, VLAN (802.1Q), STP | Switches, bridges, NICs, wireless APs | MAC flapping, VLAN mismatch, duplex mismatch, CRC errors, STP loops |
| 1 | Physical | Bit (symbol) | Transmission of raw bits over the medium; voltages, light, radio, pinouts | Ethernet PHY, RJ45, fiber, DSL, USB, Bluetooth radio | Cables, hubs, repeaters, transceivers, modems | Cable cut, no link light, bad SFP, EMI, wrong pinout, port down |
A useful shorthand: layers 1–4 are the “lower”/plumbing layers (getting bits reliably between the right ports on the right hosts), while layers 5–7 are the “upper”/application layers (making the data meaningful to the software). Network engineers live mostly in L1–L4; developers live mostly in L5–L7.
A note on the “extra” layers. In real-world practice, layers 5, 6, and 7 are blurry — the same protocol (e.g. HTTPS) spans presentation (TLS) and application (HTTP) at once. This is one reason the TCP/IP model collapses them.
The TCP/IP model and how it maps to OSI
The TCP/IP model is what the Internet actually implements (its layers were defined in RFC 1122). It comes in two common depictions — a 4-layer version and a 5-layer version (which splits the bottom layer, matching OSI more closely). Both are correct; the 5-layer version is friendlier for teaching because it separates the cable (Physical) from the framing (Data Link).
| TCP/IP (4-layer) | TCP/IP (5-layer) | OSI equivalent | Example protocols |
|---|---|---|---|
| Application | Application | 7 + 6 + 5 (App, Presentation, Session) | HTTP, DNS, TLS, SSH, SMTP |
| Transport | Transport | 4 (Transport) | TCP, UDP, QUIC |
| Internet | Internet (Network) | 3 (Network) | IP, ICMP, IPsec |
| Link / Network Access | Data Link | 2 (Data Link) | Ethernet, ARP, Wi-Fi |
| Physical | 1 (Physical) | Cables, radio, fiber |
Why real stacks are TCP/IP, not OSI:
- It shipped, and it won. TCP/IP was implemented, deployed, and iterated on the ARPANET/Internet while OSI was still a committee specification. Working code beat a perfect model.
- It’s pragmatic. The session and presentation concerns don’t need their own network layer — they’re handled by application-layer libraries (a TLS library, a JSON serializer), so collapsing them is simpler.
- The “narrow waist”. The genius of TCP/IP is IP as a universal, minimal Layer 3: any link technology below (Ethernet, Wi-Fi, 5G, satellite) and any application above (web, email, video) interoperate as long as they speak IP in the middle. This hourglass shape is why the Internet scaled.
So: use OSI for vocabulary and troubleshooting; understand that the bits on the wire follow the TCP/IP model.
Encapsulation and decapsulation
Data doesn’t teleport down the stack — each layer wraps the PDU from the layer above with its own header (and sometimes a trailer), adding the control information that layer’s peer needs. This wrapping is encapsulation on the way down (send), and decapsulation — stripping each header off — on the way up (receive). This is the single most important mechanical concept in networking.
Sending (top → bottom, encapsulation):
Application: [ Data ] (e.g. an HTTP request)
Transport: [ TCP hdr | Data ] → SEGMENT (adds src/dst ports, seq#, flags)
Network: [ IP hdr | TCP hdr | Data ] → PACKET (adds src/dst IP addresses, TTL)
Data Link: [ Eth hdr | IP hdr | TCP hdr | Data | Eth trailer ] → FRAME (adds src/dst MAC, FCS/CRC)
Physical: 0101110010101110... → BITS (encoded as electrical/optical/radio signals)
- The Transport layer chops the application data into pieces sized to fit the network (the MSS, Maximum Segment Size) and adds a TCP or UDP header → segment (TCP) / datagram (UDP).
- The Network layer adds the IP header (source and destination IP address, TTL, protocol number) → packet (a.k.a. IP datagram).
- The Data Link layer adds a header (source/destination MAC address) and a trailer (the FCS/CRC checksum for error detection) → frame.
- The Physical layer converts the frame’s bytes into bits — actual signals on copper, fiber, or air.
Receiving (bottom → top, decapsulation): the exact reverse. The NIC turns signals back into a frame, checks the FCS, and strips the Ethernet header/trailer → hands the packet up. The IP layer checks the destination IP and strips the IP header → hands the segment up. TCP checks the port, reassembles/reorders, strips its header → hands the data to the application listening on that port.
Key mental models this unlocks:
- Each layer only reads its own header. A switch (L2) reads the Ethernet header and ignores the IP payload; a router (L3) reads the IP header and rewrites the Ethernet header for the next hop; a firewall can be built to inspect any layer you want.
- MAC addresses change every hop; IP addresses (usually) don’t. As a packet crosses routers, the L2 frame is stripped and rebuilt for each link (new source/destination MAC), while the L3 IP addresses stay end-to-end. This is the classic interview insight.
- Overhead is real. Every layer’s header eats into the payload. This is why MTU (max frame size, classically 1500 bytes for Ethernet) and MSS matter, and why fragmentation or PMTUD problems cause mysterious “large requests hang” bugs.
The transport layer up close: TCP vs UDP
Layer 4 is where “networks” become “connections between programs”. Two protocols dominate.
TCP (Transmission Control Protocol) — connection-oriented, reliable, ordered, byte-stream.
- 3-way handshake to establish a connection:
- Client → Server:
SYN(seq = x) — “let’s talk, my starting sequence number is x” - Server → Client:
SYN, ACK(seq = y, ack = x+1) — “ok, and mine is y; I got yours” - Client → Server:
ACK(ack = y+1) — “got it, we’re connected” After this, both sides have agreed on sequence numbers and the connection is ESTABLISHED.
- Client → Server:
- Reliability — every byte is sequenced; the receiver ACKs what it got; unacknowledged data is retransmitted after a timeout (RTO) or on duplicate ACKs (fast retransmit).
- Ordering — segments carry sequence numbers, so out-of-order arrivals are reassembled correctly before delivery to the app.
- Flow control — the sliding window (advertised
window size) lets the receiver tell the sender “I can only buffer this much”, preventing a fast sender from overwhelming a slow receiver. - Congestion control — algorithms (slow start, congestion avoidance, e.g. CUBIC/Reno/BBR) throttle the sender based on inferred network congestion (packet loss / delay), protecting the Internet from collapse.
- Teardown — a graceful close uses
FIN/FIN, ACKin each direction (a 4-way exchange). An abrupt abort usesRST(reset) — “this connection is gone, stop talking”. ARSTin a packet capture almost always signals a problem: closed port, firewall drop, app crash, or timeout.
UDP (User Datagram Protocol) — connectionless, unreliable, message-oriented. Just source/destination ports, length, and a checksum. No handshake, no ACKs, no ordering, no congestion control. It’s a thin wrapper over IP: “fire and forget”. If you need reliability, you build it yourself on top (which is exactly what QUIC does over UDP).
| Property | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (handshake) | Connectionless |
| Reliability | Guaranteed delivery (ACK + retransmit) | Best-effort, no guarantees |
| Ordering | In-order delivery | No ordering |
| Flow / congestion control | Yes | No |
| Header size | 20+ bytes | 8 bytes |
| Speed / latency | Higher latency (setup + ACKs) | Lower latency, less overhead |
| PDU name | Segment | Datagram |
| Broadcast/multicast | No | Yes |
| Typical uses | HTTP(S), SSH, SMTP, DB connections, file transfer | DNS, DHCP, VoIP, video streaming, gaming, QUIC/HTTP-3 |
Rule of thumb: use TCP when correctness matters more than speed (loading a web page, transferring a file, a database query — a lost byte is unacceptable). Use UDP when timeliness matters more than perfection and you can tolerate/handle loss yourself (a dropped voice packet is better than a delayed one; a dropped game state update is superseded by the next one). Note that modern web is shifting to QUIC/HTTP-3, which runs reliable, ordered streams over UDP to get TCP’s guarantees without its head-of-line blocking and slow handshake.
Key Concepts
Speaking in layers: “L2 vs L3”, “L4 vs L7”
The single most practical payoff of these models is a shared vocabulary for describing where a device or decision operates.
L2 vs L3 devices (see network devices):
- A switch is fundamentally an L2 device — it forwards frames based on MAC addresses, within a single broadcast domain / LAN. It doesn’t know or care about IP.
- A router is an L3 device — it forwards packets between different networks based on IP addresses and a routing table.
- A “Layer 3 switch” is a switch with routing silicon baked in — it can do both (fast L2 switching within VLANs and L3 routing between them).
L4 vs L7 middleboxes — this distinction dominates modern infrastructure:
| L4 (Transport) load balancer / firewall | L7 (Application) load balancer / firewall | |
|---|---|---|
| Sees | IP addresses + TCP/UDP ports | Full application data (URLs, headers, cookies, HTTP methods) |
| Decisions based on | 5-tuple (src/dst IP, src/dst port, protocol) | Hostname, path, header, cookie, request content |
| Examples | AWS NLB, HAProxy in TCP mode, iptables, IPVS | AWS ALB, Nginx/Envoy, API gateways, a WAF |
| Cost | Fast, cheap, protocol-agnostic | More CPU (must parse & often terminate TLS) |
| Can do | Route “all traffic on :443 to this pool" | "Route /api/* here, /images/* there; block SQL-injection patterns” |
An L4 firewall decides “allow/deny based on IP + port” (classic stateful firewall). An L7 firewall / WAF understands the application protocol and can block, say, a malicious HTTP request even though the port is legitimately open.
Localizing faults by layer (the troubleshooting ladder)
Because the stack is layered, the professional way to debug is to isolate the failing layer bottom-up (or use divide-and-conquer). A canonical checklist:
| Layer | Question | Tool / evidence |
|---|---|---|
| L1 Physical | Is there link? Is the cable/SFP good? | Link LED, ethtool, interface counters (CRC/errors), swap cable |
| L2 Data Link | Right VLAN? MAC learned? ARP resolving? | arp -a, switch MAC table, ip neigh, check VLAN tags |
| L3 Network | Can I reach the IP? Correct route/gateway? | ping, traceroute/tracert, ip route, check subnet mask |
| L4 Transport | Is the port open/listening/reachable? | telnet host port, nc -zv, ss -tlnp, look for RST/SYN retransmits |
| L5–L7 App | Does the app answer correctly? TLS ok? | curl -v, openssl s_client, app logs, HTTP status codes |
The discipline: don’t debug the app (L7) when the cable is unplugged (L1). “It’s always DNS” is a joke precisely because engineers skip layers. ping works but curl fails → L3 is fine, look at L4/L7. ping fails by IP but the interface is up → look at L2/L3 (routing, ARP, gateway).
The upper layers in practice: session, presentation, application
In the TCP/IP world these three OSI layers are collapsed into “Application”, but the concerns are still real and worth naming:
- Session (L5) — keeping track of a logical conversation that outlives a single request. In practice: web sessions (a session cookie / JWT that ties many stateless HTTP requests to one logged-in user), TLS session resumption (avoiding a full handshake on reconnect), database connection sessions, and RPC channels. Failures look like: “I got logged out”, “token expired”, “connection dropped mid-transfer”.
- Presentation (L6) — how data is represented so both sides agree on its meaning: character encoding (UTF-8 vs Latin-1 → mojibake bugs), serialization (JSON, Protobuf, XML, MessagePack), compression (gzip, Brotli), and crucially encryption: TLS is the canonical presentation-layer service, turning a plaintext byte stream into an authenticated, encrypted one. The TLS handshake (negotiating cipher suites, exchanging certificates) is a presentation-layer concern layered on top of a TCP (transport) connection.
- Application (L7) — the protocol the software actually speaks: HTTP/HTTPS for web and APIs, DNS for name resolution, SMTP/IMAP for mail, SSH for remote shells, gRPC for service-to-service. This is where “the request” and “the response” that developers reason about actually live. Deep dives on these belong in core protocols.
A concrete example tying it together — loading https://example.com:
- DNS (L7, over UDP/L4) resolves
example.com→ an IP. - TCP (L4) 3-way handshake to the server’s IP on port 443.
- TLS (L6) handshake negotiates encryption and validates the certificate.
- HTTP (L7) request/response flows inside the encrypted TLS tunnel.
- Underneath all of it, every byte was encapsulated into TCP segments → IP packets → Ethernet/Wi-Fi frames → bits, routed hop-by-hop by routers (L3) and switched link-by-link by switches (L2).
That single URL exercises the entire stack — which is exactly why the layered model is the foundation everything else builds on.
Best Practices
- Learn OSI for vocabulary, TCP/IP for reality. When troubleshooting or in interviews, name the layer explicitly (“this is an L2 issue”) — it forces precision and speeds up communication.
- Debug bottom-up (or divide-and-conquer), not by guessing. Confirm L1/L2 before blaming the app. Use the troubleshooting ladder above so you never skip a layer.
- Memorize the PDU names and what changes per hop. “Segment → packet → frame → bits”, and “MAC changes each hop, IP stays end-to-end” are the two facts that unlock most encapsulation questions.
- Pick the right transport for the job. Default to TCP for correctness-critical flows; choose UDP (or QUIC) for latency-sensitive, loss-tolerant, or high-fanout (broadcast/multicast) traffic — and don’t reinvent reliability on UDP unless you truly need to.
- Choose L4 vs L7 middleboxes deliberately. Use L4 LBs/firewalls for raw throughput and protocol-agnostic routing; use L7 (ALB, Nginx, Envoy, WAF) when you need content-based routing, TLS termination, or application-aware security — accept the CPU cost.
- Mind the MTU/MSS. Encapsulation overhead and mismatched MTUs (VPNs, tunnels, jumbo frames) cause fragmentation and PMTUD black-hole bugs; clamp MSS on tunnels and keep path MTU consistent.
- Terminate and inspect at the right layer. Don’t try to make an L4 device do content filtering, and don’t burn L7 CPU on traffic that only needs L4 forwarding.
- Capture traffic to see the layers.
tcpdump/Wireshark literally show you each header (Ethernet → IP → TCP → payload). Reading a capture is the fastest way to internalize encapsulation and to spotRST/retransmit/handshake problems.
References
- OSI Model — Cloudflare Learning Center
- What is the OSI Model? — Cisco
- RFC 1122 — Requirements for Internet Hosts (Communication Layers)
- RFC 9293 — Transmission Control Protocol (TCP)
- RFC 768 — User Datagram Protocol (UDP)
- TCP vs UDP — Cloudflare Learning Center
- What is the Internet Protocol (IP)? — Cloudflare
- TCP/IP Model — MDN / IBM overview