system design

OSI Model Explained: 7 Layers of Networking Every Developer Should Know

The OSI model defines 7 layers of network communication. Learn what each layer does, how it maps to TCP/IP, debugging tools per layer, and why backend developers care about L3-L7.

By Akash Sharma·20 min read
#system design
#networking
#osi model
#backend
#protocols
#infrastructure
#debugging
#load balancer

The OSI model is a 7-layer framework that describes how data moves across a network — from the raw electrical signal on a wire all the way up to the HTTP request your application sends. Every layer has a name, a job, and a set of protocols responsible for that job.

Why does it matter for developers? Because when a network request fails, the OSI model tells you where it failed. "Can I ping the server?" tests Layer 3. "Can I reach port 443?" tests Layer 4. "Is the TLS certificate valid?" tests Layer 6. Without this mental model, debugging a "connection refused" error means guessing. With it, you work through the stack systematically and find the problem in minutes.

It also gives you a shared vocabulary with infrastructure engineers. When someone says "this is a Layer 7 load balancer," they mean it routes traffic based on HTTP content — not just IP and port. That distinction matters for how you architect services.

The mnemonic: Please Do Not Throw Sausage Pizza Away — Physical, Data Link, Network, Transport, Session, Presentation, Application (bottom to top).


The 7 Layers (Bottom to Top)

Think of data traveling from your computer to a server as going down the layers on your side, through the wire, then back up the layers on the server's side.

Layer 1: Physical

The actual hardware. Cables, fiber optics, radio waves, electrical voltage. This layer converts bits (0s and 1s) into electrical signals, light pulses, or radio waves and transmits them across a medium.

No intelligence here — just raw signal transmission. The Physical layer doesn't know what the bits mean; it just moves them.

Protocols/standards: Ethernet physical spec (IEEE 802.3), Wi-Fi radio (802.11), USB, Bluetooth PHY

Debugging tools at Layer 1:

  • Check cable seating and link lights on NICs/switches
  • ethtool eth0 — inspect physical link speed and duplex on Linux
  • Wi-Fi signal strength tools (OS-level or iwconfig)

Troubleshoot at this layer when: The cable is unplugged. Wi-Fi is physically too far from the router. NIC failure. Intermittent packet loss that correlates with cable movement.

Layer 2: Data Link

Layer 2 takes raw signals from Layer 1 and packages them into frames for transmission between two directly connected devices on the same network segment.

This is where MAC addresses live. Every network card has a globally unique 48-bit MAC address burned in at manufacturing. Switches — not routers — operate at Layer 2. A switch forwards frames based on MAC address tables it builds by watching traffic.

Protocols: Ethernet (IEEE 802.3), Wi-Fi (802.11), ARP (maps IP → MAC), PPP, VLAN (802.1Q)

Debugging tools at Layer 2:

  • arp -n — view ARP cache (IP to MAC mappings)
  • ip neighbor — same, newer syntax
  • tcpdump -e — show MAC addresses in packet capture
  • Switch management interfaces — check port status, MAC tables

Troubleshoot at this layer when: Two devices on the same subnet can't communicate. ARP poisoning. VLAN misconfiguration. Duplicate MAC addresses.

Layer 3: Network

Layer 3 handles routing between networks. This is where IP addresses live. Routers operate at Layer 3 — they receive packets, look up the destination IP in a routing table, and forward to the next hop.

When you send a request to a server in another country, Layer 3 is responsible for the path: your router → ISP router → backbone routers → destination network → server.

Protocols: IPv4, IPv6, ICMP (ping, traceroute), OSPF, BGP

Debugging tools at Layer 3:

  • ping <host> — ICMP echo, confirms Layer 3 reachability
  • traceroute <host> / tracert on Windows — shows each hop, identifies where packets stop
  • ip route — inspect local routing table
  • mtr <host> — combines ping + traceroute, shows per-hop packet loss

Troubleshoot at this layer when: Packets aren't routing correctly. You can ping by IP but not by hostname (DNS issue at Layer 7, but routing at Layer 3). Subnet misconfiguration. TTL exceeded errors.

Layer 4: Transport

Layer 4 handles end-to-end communication between applications, not just hosts. This is where TCP and UDP live.

TCP adds reliability: it establishes a connection (3-way handshake), assigns sequence numbers to packets, retransmits lost ones, and controls flow rate. UDP skips all that — faster, but no delivery guarantee.

Port numbers live at Layer 4. A port identifies the specific application process on a host. Port 80 = HTTP. Port 443 = HTTPS. Port 5432 = PostgreSQL. Port 6379 = Redis.

Protocols: TCP, UDP, SCTP, QUIC (technically operates at Layer 4 semantics over UDP)

Debugging tools at Layer 4:

  • telnet <host> <port> — raw TCP connection test
  • nc -zv <host> <port> — netcat port probe (cleaner than telnet for scripting)
  • ss -tlnp / netstat -tlnp — show listening ports and which processes own them
  • tcpdump port 443 — capture traffic on a specific port
  • curl -v — shows TCP connection, TLS handshake, and HTTP exchange

Troubleshoot at this layer when: Connection times out (port blocked by firewall). "Connection refused" (nothing listening on that port). TCP handshake never completes.

Layer 5: Session

Layer 5 manages sessions — opening, maintaining, and closing communication channels between applications. It handles things like authentication at the session level, session checkpointing, and reconnection after a failure.

In practice, most modern protocols (HTTP/1.1 keep-alive, HTTP/2 streams, gRPC) handle session management themselves at Layer 7 rather than relying on a distinct Layer 5. This layer is largely theoretical in modern networking — TCP/IP collapses it into the Application layer.

Protocols: NetBIOS, RPC, PPTP control channel, SQL session management

Layer 6: Presentation

Layer 6 handles data formatting, translation, and encryption. It is responsible for translating data between the format the application uses and the format needed for network transmission.

TLS/SSL encryption operates at this layer — it encrypts the payload before it goes into TCP, and decrypts it on the receiving end. Data serialization (JSON, Protocol Buffers, MessagePack) is conceptually a Layer 6 concern: translating application data structures into a transmittable format.

Protocols/formats: TLS 1.2/1.3, SSL, JPEG, MPEG, ASCII, UTF-8, JSON, Protobuf

Debugging tools at Layer 6:

  • openssl s_client -connect host:443 — inspect TLS handshake, certificate chain
  • curl -vv https://host — TLS negotiation details
  • Browser DevTools Security tab — certificate validity, cipher suite

Troubleshoot at this layer when: SSL certificate errors (CERTIFICATE_VERIFY_FAILED). TLS version mismatch. Data encoding errors (garbled characters, wrong charset).

Layer 7: Application

The layer you interact with as a developer every day. HTTP, HTTPS, DNS, SMTP, FTP, gRPC, WebSocket — these are all Layer 7 protocols.

Your web application, REST API, database client, and browser all operate at Layer 7. When you write fetch('https://api.example.com/users'), you're working at Layer 7 — the layers below handle getting those bytes to their destination.

Protocols: HTTP/1.1, HTTP/2, HTTP/3, DNS, SMTP, FTP, IMAP, gRPC, WebSocket, MQTT

Debugging tools at Layer 7:

  • curl -v — full HTTP request/response with headers
  • dig / nslookup — DNS resolution
  • Wireshark with HTTP filter — full packet-level HTTP inspection
  • Browser DevTools Network tab
  • Application logs, APM tools (Datadog, New Relic)

Troubleshoot at this layer when: 404 errors, 500 errors, authentication failures, API timeouts, malformed request/response bodies, DNS resolution failures.


The 7 Layers as a Table

LayerNameKey ProtocolsUnit of DataWhat It Does
7ApplicationHTTP, DNS, SMTP, gRPCMessageUser-facing protocols, app logic
6PresentationTLS, JSON, ProtobufMessageEncryption, serialization, encoding
5SessionNetBIOS, RPCMessageSession open/close/checkpointing
4TransportTCP, UDP, QUICSegment / DatagramEnd-to-end delivery, ports, reliability
3NetworkIP, ICMP, BGPPacketRouting between networks, IP addressing
2Data LinkEthernet, ARP, Wi-FiFrameHop-to-hop delivery, MAC addressing
1PhysicalCopper, Fiber, RadioBitRaw bit transmission over medium

OSI Model vs TCP/IP Model

The OSI model is a conceptual framework — it was designed by ISO in 1984 to standardize network communication theory. TCP/IP is what networks actually use. It was developed by DARPA in the 1970s and became the foundation of the internet.

TCP/IP collapses OSI's 7 layers into 4 by merging the ones that overlap in practice:

TCP/IP LayerOSI EquivalentWhat It Covers
ApplicationLayers 5 + 6 + 7HTTP, DNS, TLS, session management
TransportLayer 4TCP, UDP, QUIC
InternetLayer 3IP, ICMP, routing
Network Access (Link)Layers 1 + 2Ethernet, Wi-Fi, ARP, physical medium

Why OSI still matters if TCP/IP is what's used: OSI gives you finer-grained vocabulary. Saying "this is a Layer 7 problem" is more precise than "this is an Application layer problem" because it signals exactly what level of the stack you're debugging — and it's universally understood by any networking engineer, regardless of the protocol stack they work with.

The two models aren't competing — OSI is the map, TCP/IP is the territory. You use OSI to think and discuss; you use TCP/IP to actually transmit data.


Encapsulation and Decapsulation

Encapsulation is how data gets packaged as it travels down the OSI stack on the sender's side. Each layer adds its own header (and sometimes trailer) to the data from the layer above. Decapsulation is the reverse — stripping those headers as data travels up the stack on the receiver's side.

How a packet is built (sender side, Layer 7 → Layer 1)

plaintext
Layer 7 (Application):
  [HTTP Request Data]
 
Layer 6 (Presentation) — TLS encrypts:
  [TLS Record | Encrypted HTTP Data]
 
Layer 4 (Transport) — TCP adds segment header:
  [TCP Header: src port, dst port, seq#, ack#, flags | TLS Record | Data]
 
Layer 3 (Network) — IP adds packet header:
  [IP Header: src IP, dst IP, TTL, protocol | TCP Segment]
 
Layer 2 (Data Link) — Ethernet adds frame:
  [Ethernet Header: src MAC, dst MAC, EtherType | IP Packet | Ethernet Trailer (FCS)]
 
Layer 1 (Physical):
  01001101 00110101 ... (bits transmitted as electrical/optical signals)

Packet structure summary table

LayerAdded ByHeader ContainsData Unit Name
7-5ApplicationHTTP method, URL, headersMessage
6TLSRecord type, version, lengthTLS Record
4TCPSrc/dst port, seq, ack, flagsSegment
3IPSrc/dst IP, TTL, protocolPacket
2EthernetSrc/dst MAC, EtherType, FCSFrame
1NIC/PHYPreamble, physical encodingBits

On the receiver's side, each layer strips its own header, processes the information, and passes the payload up. The server's NIC strips the frame, the OS IP stack strips the IP header, TCP strips the TCP header, and your application reads the HTTP request.


Each Layer in Practice

Real packet examples and debugging by layer

Layer 1 — Ethernet link check:

bash
ethtool eth0
# Speed: 1000Mb/s
# Duplex: Full
# Link detected: yes

If "Link detected: no" — cable or NIC issue.

Layer 2 — ARP resolution:

bash
ping 192.168.1.1    # triggers ARP if not cached
arp -n
# ? (192.168.1.1) at aa:bb:cc:dd:ee:ff [ether] on eth0

If no ARP entry appears after ping — Layer 2 problem (same subnet but no response).

Layer 3 — ICMP reachability:

bash
ping api.example.com
traceroute api.example.com
# 1. 192.168.1.1 (gateway)   1.2ms
# 2. 10.0.0.1 (ISP)          5.1ms
# 3. ...
# 10. api.example.com        42ms

Traceroute shows where packets stop — the hop that doesn't respond is the routing problem.

Layer 4 — TCP port probe:

bash
nc -zv api.example.com 443
# Connection to api.example.com 443 port [tcp/https] succeeded!
 
nc -zv api.example.com 5432
# nc: connect to api.example.com port 5432 (tcp) failed: Connection refused

"Connection refused" = nothing listening on that port. Timeout = firewall is dropping packets silently.

Layer 6 — TLS inspection:

bash
openssl s_client -connect api.example.com:443
# ...
# Certificate chain:
#  0 s:CN=api.example.com
#    i:C=US, O=Let's Encrypt, CN=R3
# SSL handshake has read 4120 bytes ...
# Verify return code: 0 (ok)

Non-zero verify return code = TLS certificate problem.

Layer 7 — Full HTTP trace:

bash
curl -v https://api.example.com/users
# * TCP_NODELAY set
# * Connected to api.example.com (93.184.216.34) port 443
# * TLS 1.3, cipher TLS_AES_256_GCM_SHA384
# > GET /users HTTP/2
# > Host: api.example.com
# < HTTP/2 200

Troubleshooting with the OSI Model

The OSI model's greatest practical value is giving you a systematic debug methodology. Start at the bottom. Eliminate each layer before moving up. Never jump to Layer 7 debugging while the cable is unplugged.

The systematic approach

plaintext
Layer 1 — Physical
  Q: Is there a physical link?
  Test: Check LEDs, run ethtool, check cable
  Pass → continue. Fail → fix hardware first.
 
Layer 2 — Data Link
  Q: Can I reach the default gateway (same subnet)?
  Test: ping <gateway IP>, check arp -n for gateway MAC
  Pass → continue. Fail → ARP/switching/VLAN issue.
 
Layer 3 — Network
  Q: Can I reach the destination IP?
  Test: ping <server IP>, traceroute <server IP>
  Pass → continue. Fail → routing/firewall issue between subnets.
 
Layer 4 — Transport
  Q: Can I reach the destination port?
  Test: nc -zv <host> <port>, telnet <host> <port>
  Pass → continue. Fail → port blocked by firewall, or service not running.
 
Layer 6 — Presentation (for HTTPS)
  Q: Is TLS valid and negotiating correctly?
  Test: openssl s_client -connect <host>:443
  Pass → continue. Fail → expired certificate, wrong CA, TLS version mismatch.
 
Layer 7 — Application
  Q: Is the application returning the right response?
  Test: curl -v, check HTTP status codes, review app logs

Common failures at each layer

LayerCommon FailureSymptomFix
1Unplugged cableNo link light, no trafficReseat cable
2ARP failureCan't reach gatewayCheck VLAN, check ARP table
3Missing routeping fails, traceroute stopsAdd route, check firewall rules
4Port blockedConnection timeout / refusedOpen firewall port, check service is running
6Expired TLS certSSL_ERROR_RX_RECORD_TOO_LONG, browser warningRenew certificate
7App crash500 error, empty responseCheck application logs

OSI in Backend Development

As a backend developer, you rarely think about Layers 1 and 2 — those are handled by your cloud provider's network and OS. The layers that matter for your day-to-day work are Layer 3 through Layer 7.

Layer 3 (Network) — IP and routing

You interact with Layer 3 when configuring:

  • VPC routing tables in AWS/GCP/Azure
  • Security group rules (which IPs can reach your service)
  • Service mesh policies (Istio, Linkerd route at Layer 3/4)
  • CIDR blocks and subnet design

Layer 4 (Transport) — TCP, UDP, ports

Layer 4 is where you make decisions about:

  • Connection pooling: TCP connections are expensive to establish (3-way handshake). Your database client's connection pool keeps Layer 4 connections open and reuses them.
  • Timeouts: TCP connect timeout vs. read timeout are both Layer 4 concerns.
  • Load balancing: A Layer 4 load balancer forwards TCP connections based on IP + port. It doesn't inspect what's inside the packet — just routes the TCP stream. This is faster but dumber.

Layer 6 (Presentation) — TLS

TLS sits between Layer 4 and Layer 7. It's technically Layer 6, and it's one of the most important security concerns for backend developers:

  • TLS termination: where does TLS end? At the load balancer, at the service, or end-to-end?
  • mTLS (mutual TLS): both client and server authenticate with certificates — used in service mesh and zero-trust architectures.
  • Certificate rotation: certs expire. Automate renewal (Let's Encrypt + certbot, AWS ACM).

Layer 7 (Application) — HTTP and your API

Everything your application code does lives at Layer 7:

  • HTTP routing (which path → which handler)
  • Authentication headers, API keys, JWTs
  • Rate limiting, retries, circuit breakers

A Layer 7 load balancer can inspect HTTP content — it can route /api/v2/* to one service and /static/* to another, add/strip headers, handle sticky sessions based on cookies, and terminate TLS. This is what AWS ALB, Nginx, and Envoy do. More powerful than L4, but slightly higher latency due to the inspection overhead.

L4 vs L7 Load Balancing — At a Glance

FeatureL4 Load BalancerL7 Load Balancer
Routes based onIP + PortIP + Port + HTTP headers/URL/cookies
Can inspect payloadNoYes
TLS terminationNo (TCP passthrough)Yes
Path-based routingNoYes
Sticky sessionsBasic (IP hash)Cookie-based
ExamplesAWS NLB, HAProxy (TCP)AWS ALB, Nginx, Envoy, Traefik
PerformanceLower latencySlightly higher latency
Use whenLow latency critical (gaming, IoT)HTTP services, microservices

How It Works in Practice: Loading a Web Page

  1. Layer 7: Your browser creates an HTTP/2 GET request for example.com
  2. Layer 6: The request gets encrypted with TLS 1.3
  3. Layer 5: A session is implicitly tracked (HTTP/2 handles this internally)
  4. Layer 4: TCP wraps the data with source and destination ports (ephemeral port → port 443); 3-way handshake already completed
  5. Layer 3: IP header added with your IP and the server's IP; routers find the path hop-by-hop
  6. Layer 2: Ethernet frames carry the IP packet from your NIC to your gateway, then hop-by-hop between routers
  7. Layer 1: Electrical signals travel down the cable to your router; fiber pulses traverse the backbone

On the server side, this stack unwinds in reverse. Your application code at Layer 7 never sees any of the layers below — the OS and NIC handle it transparently.


Key Takeaways

  • OSI has 7 layers, each with a specific job in moving data across networks
  • Layers 1–4 handle how data is transmitted; layers 5–7 handle what data means
  • Port numbers live at Layer 4 (Transport); IP addresses at Layer 3 (Network); MAC addresses at Layer 2 (Data Link)
  • TCP and UDP are Transport layer (Layer 4) protocols; HTTP/DNS/gRPC are Layer 7
  • TCP/IP collapses OSI's 7 layers into 4 — that's what networks actually implement
  • TLS/SSL sits at Layer 6 — encrypts payload before TCP carries it
  • Layer 4 load balancers route TCP streams by IP+port; Layer 7 load balancers route by HTTP content
  • Systematic debugging: start at Layer 1, eliminate each layer before moving up

FAQ

What is the OSI model and what are the 7 layers?

The OSI (Open Systems Interconnection) model is a conceptual framework that divides network communication into 7 layers, each with a defined role. Bottom to top: (1) Physical — raw bit transmission over a medium; (2) Data Link — hop-to-hop framing with MAC addresses; (3) Network — IP routing between networks; (4) Transport — end-to-end delivery with TCP/UDP and port numbers; (5) Session — session management; (6) Presentation — encryption and data formatting (TLS, JSON); (7) Application — user-facing protocols like HTTP, DNS, SMTP.

What is the difference between OSI model and TCP/IP model?

OSI is a 7-layer theoretical model developed by ISO for standardization. TCP/IP is a 4-layer practical model (Application, Transport, Internet, Network Access) that is actually implemented in all modern networks. TCP/IP merges OSI layers 5+6+7 into one Application layer, and merges OSI layers 1+2 into one Network Access layer. Engineers use OSI as a precise vocabulary for discussing problems and TCP/IP as the actual protocol stack.

Which OSI layer does HTTP operate on?

HTTP operates at Layer 7 — the Application layer. When you make an HTTP request, your browser is working at Layer 7. The layers below (TLS at L6, TCP at L4, IP at L3, Ethernet at L2) handle getting those HTTP bytes to their destination without your application code needing to know anything about them.

Which OSI layer does a load balancer work at?

It depends on the type. A Layer 4 load balancer (e.g., AWS NLB, HAProxy in TCP mode) routes traffic based on IP address and TCP/UDP port without inspecting the payload. A Layer 7 load balancer (e.g., AWS ALB, Nginx, Envoy) inspects HTTP headers, URLs, and cookies to make routing decisions — enabling path-based routing, header manipulation, TLS termination, and sticky sessions. Most web applications use L7 load balancers.

How do I use the OSI model to debug network issues?

Start at Layer 1 and work up. (1) Check physical connection and link lights. (2) Ping the default gateway to verify Layer 2/3 on the local network. (3) Ping or traceroute the destination IP to verify Layer 3 routing. (4) Use nc -zv host port to verify the destination port is open (Layer 4). (5) Use openssl s_client -connect host:443 to verify TLS (Layer 6). (6) Use curl -v to test the HTTP response (Layer 7). Each step eliminates one layer as the source of the problem.

What is the difference between Layer 4 and Layer 7 load balancing?

A Layer 4 load balancer routes TCP/UDP connections based on IP and port only — it never looks inside the packet. It's fast and protocol-agnostic. A Layer 7 load balancer reads the HTTP request (method, URL, headers, cookies) before routing. This allows path-based routing (/api → service A, /static → CDN), host-based routing (virtual hosting), header injection, TLS termination, and cookie-based session affinity. L7 is more flexible but adds a small amount of latency due to packet inspection. Use L4 when you need raw TCP throughput (databases, gaming); use L7 for HTTP microservices.

Why do engineers still learn the OSI model if TCP/IP is what's actually used?

Two reasons. First, precision: OSI layers give engineers an exact, shared vocabulary. Saying "this is a Layer 4 problem" communicates more precisely than "this is a transport problem." Second, OSI covers concepts that TCP/IP abstracts away — like the distinction between session management (L5) and presentation/encryption (L6) — which matters when you're designing protocols, debugging TLS issues, or explaining where in a stack a particular responsibility lives. The OSI model is the reference; TCP/IP is the implementation.


Related reading: TCP, UDP, HTTP, gRPC Explained · DNS Explained

Enjoyed this article?

Get weekly insights on backend architecture, system design, and Go programming.