The OSI model splits network communication into seven layers, from the bits on a cable (layer 1) up to the HTTP request your code sends (layer 7). Each layer does one job and talks only to its neighbours above and below, so a failure or a design choice can be pinned to a single layer. ISO defined it as the Basic Reference Model (ISO/IEC 7498-1).

In this article we follow one example the whole way: a student in Warangal submits a scholarship form from a phone to a server in a data centre. We look at what every layer adds, what a router really touches, how a lost segment is repaired and which layer notices a damaged bit. Six runnable programs in Java (with Python and C++ versions) give real numbers for each step.

Key takeaways

  • A 54-byte JSON form became 262 byte-times on the wire. Only 20.6% of that was the form itself; a 20-byte message was 8.7% useful and a 1,000-byte body 82.6%.

  • A router reads only the layer 3 header. Across three routers the TTL went from 64 to 61 and the header checksum was recomputed each time, while the IP packet inside stayed the same and only the frame around it changed.

  • The subnet mask decides who gets the frame. A server on another network is reached through the gateway's MAC address, and a wrong /25 mask sent a neighbour on the same Wi-Fi through the router too.

  • One lost segment out of six caused four duplicate ACKs. Fast retransmit repaired it in 2 round trips (80 ms) instead of waiting 240 ms for a timer.

  • Each layer checks a different thing. The Ethernet CRC caught a damaged cable, the IP checksum a damaged header, the TCP checksum damage inside a router, and only an application-level check caught two swapped words.

  • Walking the layers from the bottom up, eight probes named the broken layer in every failure we simulated.

1. What Is the OSI Model?

A network trip has many separate jobs: turning bits into signals, finding the next device, finding the right machine, delivering to the right program, encrypting, and finally making sense of the message. The OSI model gives each job its own layer. A layer uses the service of the layer below it and offers a service to the layer above it, and the same layer on the other machine reads the header that its twin wrote.

One honest warning before we start. The internet does not run OSI software; it runs TCP/IP, which has four layers (we compare the two later). OSI is still worth learning because its names are the shared vocabulary of every system design discussion: layer 4 load balancer, layer 7 proxy, layer 3 firewall rule.

This lesson follows Single Point of Failure and opens the networking section. Later lessons zoom in on one layer at a time: IP Address, TCP vs UDP, HTTP/HTTPS and DNS.

2. The Scenario We Will Follow

A student in Warangal fills in a scholarship form and taps Submit. The phone is on home Wi-Fi, the router connects to the internet service provider, and the server forms.scholarhub.example sits in a Hyderabad data centre. The addresses below are made up from ranges that are reserved for documentation, so they never point at a real machine.

DeviceIP addressMAC addressRole
Student phone192.168.29.2302:1a:4b:00:c1:23Sends the form
Wi-Fi router192.168.29.102:1a:4b:00:00:01Default gateway of the home network
Server198.51.100.40not visible from the phoneReceives it on port 443

Two kinds of address already appear. The IP address names a machine on the internet and survives the whole trip. The MAC address names a network card on one link only and is replaced at every hop. Keeping these two apart explains most of what follows.

3. The Seven Layers at a Glance

Read the stack from the top, where your code lives, down to the cable. Software developers spend their time in layers 7 to 5, the operating system handles layers 4 and 3, and network hardware handles layers 2 and 1.

LayerJobUnit and address
7 ApplicationDefines what messages meanMessage, URL or host name
6 PresentationEncoding, compression, encryptionData, no address
5 SessionStarts, keeps and ends a dialogueData, session id
4 TransportProcess to process deliverySegment or datagram, port
3 NetworkMachine to machine across networksPacket, IP address
2 Data LinkDelivery over one linkFrame, MAC address
1 PhysicalSignals on the mediumBit, no address

The same layers again, with real protocols and the place you meet each one in Java.

LayerExamplesWhere you meet it in Java
7 ApplicationHTTP, DNS, SMTP, gRPC, WebSocketjava.net.http.HttpClient, Spring controllers
6 PresentationJSON, UTF-8, gzip, TLS recordsSSLContext, SSLSocket, JSON libraries
5 SessionLogin sessions, cookies, TLS resumptionHttpSession in a servlet container
4 TransportTCP, UDP, QUICSocket, ServerSocket, DatagramSocket
3 NetworkIPv4, IPv6, ICMPInetAddress
2 Data LinkEthernet, Wi-Fi, ARPNetworkInterface
1 PhysicalCopper, fibre, radionot visible

A way to remember the order from the top is All People Seem To Need Data Processing: Application, Presentation, Session, Transport, Network, Data link, Physical.

4. Layer 1: Physical

Layer 1 moves raw bits as electrical voltage on copper, light pulses in fibre or radio waves in Wi-Fi. It knows nothing about addresses or meaning. For system design its main lesson is a physical one: signals take time. Light in fibre covers roughly 200,000 km each second, so a round trip between two cities has a floor that no software can beat.

5. Layer 2: Data Link

Layer 2 delivers data between two devices on the same link, for example the phone and the router. The unit is a frame: a header with the destination and source MAC addresses, the payload, and a 4-byte check value at the end called the frame check sequence. A switch reads the destination MAC and sends the frame out of one port only, after learning which MAC sits behind which port. A hub, by contrast, repeats every bit out of every port.

The phone knows the router's IP address (192.168.29.1) but a frame needs a MAC address. ARP solves that with a broadcast question and a direct answer. IPv6 uses a similar mechanism called Neighbor Discovery.

6. Layer 3: Network

Layer 3 moves a packet from one machine to another across many networks. The IP header carries the source and destination IP addresses, a time-to-live counter (TTL) and a header checksum. Routers read that header, look up the next hop and forward the packet. The packet is the part that survives the journey; the frame around it is rebuilt at every hop. Layer 3 also holds ICMP, the protocol behind ping and the "time exceeded" messages used by traceroute.

7. Layer 4: Transport

Layer 3 gets a packet to the right machine; layer 4 gets the data to the right program on that machine using a port number. Our server listens on port 443 and the phone picked a temporary port such as 51234. TCP adds a connection, ordering, retransmission and flow control, and cuts big messages into segments. UDP adds only ports and a checksum. The two are compared in TCP vs UDP. In Java this is the layer of Socket and DatagramSocket.

8. Layers 5, 6 and 7: Session, Presentation and Application

In the OSI drawing the top three layers are separate. In real software they blur into one: your application plus its libraries. Layer 7 is the protocol your program speaks, such as HTTP or DNS. Layer 6 is how data is represented: JSON or UTF-8 encoding, compression such as gzip, and encryption. Layer 5 is the dialogue: opening it, keeping it alive, ending it.

Two protocols do not fit the boxes cleanly, and it is better to say so than to force them. TLS encrypts (a presentation job), keeps session keys and resumes sessions (a session job) and sits between TCP and HTTP; textbooks put it at layer 6 or 5, and many engineers simply call it "between 4 and 7". WebSocket starts as an HTTP request and then keeps one connection open for messages, so it is an application protocol. It is not a layer 5 protocol, even though a long-lived connection feels like a session.

HTTP and HTTPS are covered in HTTP/HTTPS, and name lookup in DNS.

9. One Request From Start to Finish

Putting the layers in order of time, tapping Submit triggers a short chain of events. Notice that the lower layers get their work done first, and that DNS, ARP, TCP and TLS each finish before the first byte of the form is sent.

10. Wrapping the Message: Encapsulation With Real Byte Counts

Going down the stack, each layer wraps what it received in its own header (and the data link layer adds a trailer too). This is encapsulation. The receiver unwraps in reverse order, which is decapsulation. Every wrapper costs bytes, and for small messages that cost dominates.

The program below builds the real HTTP request text for our form, adds the TLS record overhead (5 bytes of record header, 1 content-type byte and a 16-byte authentication tag), then the TCP and IPv4 headers without options, and the Ethernet header, frame check and line overhead. The last table shows what share of the wire time is the message itself.

Output

Layer 7  JSON body          54 bytes
Layer 7  HTTP request       162 bytes  (+108 header)
Layer 6  TLS record         184 bytes  (+22 record overhead)
Layer 4  TCP segment        204 bytes  (+20 header)
Layer 3  IP packet          224 bytes  (+20 header)
Layer 2  Ethernet frame     242 bytes  (+18 header and check)
Layer 1  time on the wire   262 byte-times  (+20 preamble and gap)
Overhead for this form: 208 of 262 byte-times

body bytes  wire byte-times  useful share
20          228              8.7%
54          262              20.6%
200         409              48.8%
1000        1210             82.6%

Dry run. The JSON body is 54 bytes. The HTTP layer adds a request line and three headers, 108 bytes, so the message is 162. TLS adds 22, giving 184. TCP adds 20 (204), IP adds 20 (224), and the Ethernet header (14) plus check value (4) make a 242-byte frame. The preamble (8) and the mandatory gap between frames (12) add 20 more byte-times, so the line is busy for 262 byte-times. The form is 54 of them, which is 20.6%. A 20-byte body would have given 8.7%, because the 108 bytes of HTTP header and the rest do not shrink.

This is one reason chatty APIs are costly: ten tiny calls pay ten times the wrapper. It is also why batching and keeping a connection open matter, a topic for the HTTP lesson.

11. What a Router Touches

A router works at layer 3. It receives a frame, strips it, reads the IP header, lowers the TTL by one, looks up the next hop, and sends the same packet inside a brand-new frame for the next link. It never opens the TCP segment or the HTTP request. The TTL prevents a routing loop from circulating a packet forever: when it reaches zero the router drops the packet and reports it with ICMP.

Because the TTL is part of the IP header, the header checksum has to change at every hop. The program computes the checksum of the real header of our packet (total length 224 bytes), then simulates three routers. It updates the checksum in two ways: a full recomputation, and the incremental shortcut from RFC 1624 that routers use in hardware.

Output

client sends   TTL 64  checksum 0x15B7  valid=true
router-1 fwd   TTL 63  checksum 0x16B7  incremental 0x16B7  same=true
router-2 fwd   TTL 62  checksum 0x17B7  incremental 0x17B7  same=true
router-3 fwd   TTL 61  checksum 0x18B7  incremental 0x18B7  same=true
server checks  valid=true
after a bit flip in the source address  valid=false

Dry run. The header words are 4500, 00E0 (224), 1C46, 4000, 4006 (TTL 64, protocol 6), 0000 (checksum placeholder), C0A8, 1D17, C633 and 6428. Their sum is 0x2EA46. The carry (0x2) is added back into the low 16 bits to give 0xEA48, and the bitwise complement is 0x15B7, the checksum. Each router lowers the high byte of the fifth word by one, which raises the checksum by 0x0100, so the values are 0x16B7, 0x17B7 and 0x18B7. The server's check passes. Flipping one bit of the source address makes the sum of all ten words differ from 0xFFFF, so the next router that checks would drop the packet.

12. Same Network or Through the Gateway?

Before sending, the phone asks one question using its own IP address and subnet mask: is the destination on my network? If yes, it uses ARP to find that device's MAC address and sends the frame straight to it. If no, it puts the gateway's MAC address on the frame and leaves the destination IP unchanged, because the gateway will carry it onward.

Output

destination      mask  network          broadcast        same network  next hop        frame goes to
192.168.29.80    /24   192.168.29.0     192.168.29.255   yes           192.168.29.80   02:1a:4b:00:00:50
198.51.100.40    /24   192.168.29.0     192.168.29.255   no            192.168.29.1    02:1a:4b:00:00:01
192.168.30.7     /24   192.168.29.0     192.168.29.255   no            192.168.29.1    02:1a:4b:00:00:01
192.168.28.9     /23   192.168.28.0     192.168.29.255   yes           192.168.28.9    02:1a:4b:00:00:09
192.168.29.200   /25   192.168.29.0     192.168.29.127   no            192.168.29.1    02:1a:4b:00:00:01
192.168.29.255   /24   192.168.29.0     192.168.29.255   yes           192.168.29.255  ff:ff:ff:ff:ff:ff (everyone)

Dry run. With a /24 mask the phone's network is 192.168.29.0, and 198.51.100.40 falls in 198.51.100.0, so it goes to the gateway 02:1a:4b:00:00:01. With /23 the network widens to 192.168.28.0 to 192.168.29.255, so 192.168.28.9 is on the same network and gets its own MAC. With a wrong /25 mask the network shrinks to 192.168.29.0 to 192.168.29.127, so a printer at 192.168.29.200 looks like it is on another network and traffic to it takes an extra trip through the router. The address 192.168.29.255 is the broadcast address of the /24 network, so the frame goes to everyone.

Addressing continues in the next lesson, IP Address. The point here is that a layer 3 decision picks the layer 2 destination.

13. Cutting a Response Into Segments

Ethernet usually allows 1,500 bytes of payload in a frame, the MTU. After 20 bytes of IP header and 20 bytes of TCP header, 1,460 bytes remain for data, the MSS. A larger response is cut into segments of at most that size, and the receiver acknowledges the next byte it expects. If a segment is lost, the receiver keeps repeating the same acknowledgement.

The program sends an 8,000-byte response, loses the second segment on its first trip and replays what the client acknowledges. The timings are assumptions stated in the code: a 40 ms round trip and a 200 ms retransmission timer.

Output

response 8000 bytes, MSS 1460 -> 6 segments
server sends segment 1  seq 1-1460  (1460 bytes)
server sends segment 2  seq 1461-2920  (1460 bytes)  <- lost on the way
server sends segment 3  seq 2921-4380  (1460 bytes)
server sends segment 4  seq 4381-5840  (1460 bytes)
server sends segment 5  seq 5841-7300  (1460 bytes)
server sends segment 6  seq 7301-8000  (700 bytes)
client got segment 1               -> ACK 1461
client got segment 3 out of order  -> ACK 1461  (duplicate 1)
client got segment 4 out of order  -> ACK 1461  (duplicate 2)
client got segment 5 out of order  -> ACK 1461  (duplicate 3)
client got segment 6 out of order  -> ACK 1461  (duplicate 4)
third duplicate ACK: server resends segment 2 at once (fast retransmit)
client got segment 2 again       -> ACK 8001  (everything is in order)
segments sent 7, ACKs 6
time with fast retransmit 80 ms, with a timeout instead 240 ms (RTT 40 ms, timer 200 ms)

Dry run. 8,000 bytes divided into 1,460-byte pieces gives five full segments (7,300 bytes) and one of 700, so six segments. Segment 1 arrives and the client asks for byte 1461. Segment 2 is lost. Segments 3, 4, 5 and 6 arrive out of order, and each one makes the client repeat "I still need 1461": four duplicate ACKs. At the third one the server resends segment 2 without waiting for a timer. When it arrives, the client already holds everything up to 8000, so it answers ACK 8001. The repair cost one extra round trip, 80 ms in total; relying on the timer would have taken 240 ms.

14. Which Layer Notices a Damaged Frame?

Different layers protect different parts, and they do not repeat each other's work. The Ethernet frame check (CRC32) protects one link and is rebuilt at every hop. The IP header checksum protects the header only. The TCP checksum covers the segment and a pseudo header with the addresses, and it is verified only at the destination. An application can add its own check, and TLS authenticates every record with a tag. The Checksums lesson goes deeper into these checks.

The program builds a real 78-byte frame with correct checksums, then damages it in four ways and runs all four checks. The "router memory" cases mimic corruption after the link check has passed: the router rebuilds a fresh frame check over the damaged bytes, so layer 2 cannot see it.

Output

frame 78 bytes, FCS B322C1CB, IP checksum 1656, TCP checksum 12CB, body CRC32 EEB2161F
what happened to the frame                  L2    L3    L4    L7    first to notice
untouched                                   ok    ok    ok    ok    nobody
bit flips on the cable                      FAIL  ok    FAIL  FAIL  layer 2
router memory flips a bit in the IP header  ok    FAIL  FAIL  ok    layer 3
router memory flips a payload bit           ok    ok    FAIL  FAIL  layer 4
router memory swaps two payload words       ok    ok    ok    FAIL  layer 7

Dry run. A bit flipped on the cable breaks the frame check, so layer 2 drops the frame and nothing above ever sees it. When a router's memory flips a bit in the IP header and the frame check is recomputed afterwards, layer 2 passes but the IP header checksum fails, so layer 3 notices. A flipped payload bit in router memory passes both of those and is caught by the TCP checksum. The last case swaps two 16-bit words of the payload: the TCP checksum is a plain sum, and a sum does not change when its terms swap places, so layer 4 passes the damaged data. Only the application's own CRC32 caught it. The lesson is that no single layer is enough for data you cannot lose, which is why important systems add an end-to-end check on top.

15. OSI Model vs TCP/IP Model

The TCP/IP model, described in RFC 1122, has four layers. It merges the top three OSI layers into one application layer, keeps transport and internet (network) layers, and merges the bottom two OSI layers into one link layer.

OSI modelTCP/IP modelTypical protocols
7 Application, 6 Presentation, 5 SessionApplicationHTTP, DNS, TLS, gRPC
4 TransportTransportTCP, UDP
3 NetworkInternetIP, ICMP
2 Data Link, 1 PhysicalLinkEthernet, Wi-Fi, ARP

Use OSI numbers when you talk to other engineers ("a layer 7 load balancer") and TCP/IP when you describe what the software actually does.

16. Layer 4 vs Layer 7 in System Design

The most common reason the OSI model appears in a design review is the choice between a layer 4 and a layer 7 component. A layer 4 load balancer decides using only the IP addresses and ports, so it can forward a connection without understanding the message. A layer 7 load balancer terminates the connection, reads the HTTP request and can route by host name, path, header or cookie.

ComponentWorks atCan decide usingCosts
SwitchLayer 2MAC addressVery cheap, stays inside one network
Router, security group, network ACLLayer 3 and 4IP address, port, protocolCheap; cannot see the request
Layer 4 load balancerLayer 4IP address, portFast, little CPU, no content routing
Layer 7 load balancer, reverse proxy, API gatewayLayer 7Host name, path, headers, cookiesMore CPU, can route, cache, rate limit and rewrite
Web application firewall, CDNLayer 7Request contentCan block or cache by content

A layer 7 device that terminates TLS has to hold the certificate, which also makes it a place to inspect traffic. Pick layer 4 when you only need to spread connections quickly, and layer 7 when the decision depends on what the request says. More on proxies in Proxy vs Reverse Proxy.

17. Troubleshooting With the Layers

The model earns its keep when something breaks. A layer only works if every layer below it works, so test from the bottom up and stop at the first failure. The failing probe names the layer and narrows the cause to a short list.

Output

Wi-Fi switched off        stops after 1 probes at "link is up" -> layer 1 Physical: check cable, Wi-Fi switch, port light
wrong gateway typed in    stops after 2 probes at "gateway answers ARP" -> layer 2 Data Link: check wrong gateway address, VLAN, switch port
ISP outage                stops after 4 probes at "ping 198.51.100.40" -> layer 3 Network: check routing, ISP, security group or ACL for ICMP
DNS server down           stops after 5 probes at "resolve forms.scholarhub.example" -> layer 7 Application (DNS): check DNS server, record, resolver setting
firewall blocks port 443  stops after 6 probes at "TCP connect to 198.51.100.40:443" -> layer 4 Transport: check firewall, security group, nothing listening on the port
certificate expired       stops after 7 probes at "TLS handshake finishes" -> layer 6 Presentation (TLS): check expired certificate, wrong host name, protocol version
app returns HTTP 500      stops after 8 probes at "HTTP answers 200" -> layer 7 Application (HTTP): check application error, bad deploy, upstream failure
everything healthy        all 8 probes pass: read the application logs

Dry run. Take "DNS server down". The link is up, the gateway answers ARP, and the gateway and server both reply to ping, so probes 1 to 4 pass. Probe 5, resolving the host name, fails, so the program stops after 5 probes and reports layer 7, DNS. The same program with the firewall blocking port 443 passes the first five probes and fails the sixth, a TCP connect, which points at layer 4. In real life you would also try the server by IP address; that is how you prove DNS is the culprit when everything below it is fine.

Two Java habits follow from this. Set a separate timeout for each stage: a connect timeout (layer 4), a TLS handshake timeout and a read timeout (layer 7). And log which stage failed, so the first look at an incident already points to a layer.

18. Common Mistakes

  • Calling the internet an OSI stack. Real stacks follow TCP/IP; OSI is a reference model. Do not hunt for a layer 5 "session" box in a packet capture.

  • Putting WebSocket at layer 5. WebSocket is an application protocol that begins with an HTTP upgrade. Many tutorials make the same slip.

  • Saying gzip is a layer 6 service in HTTP. HTTP content encoding is a feature of the HTTP protocol, so in practice it sits at layer 7; the presentation layer is a way of grouping the job, not a separate piece of software.

  • Thinking the MAC address travels to the server. It is replaced at every hop. The IP packet is what survives.

  • Believing "ping works, so the site works". Ping tests layer 3. A closed port, an expired certificate and a failing application all leave ping fine.

  • Trusting one checksum. The TCP checksum missed swapped words in our experiment; use TLS or an application check for data that matters.

  • Calling every proxy layer 7. A TCP proxy forwards bytes at layer 4 and never reads HTTP.

19. Best Practices

  • Name the layer when you name a component: say layer 4 or layer 7 load balancer, not just load balancer.

  • Choose health checks at the layer of the dependency: a TCP connect proves the port is open, an HTTP check proves the app answers.

  • Keep messages large enough to be worth their headers, and reuse connections.

  • Put filtering at the cheapest layer that can express it: network rules for addresses and ports, a layer 7 firewall for request content.

  • Add an end-to-end integrity check for data you cannot lose.

  • Troubleshoot from the bottom up and write down the first failing layer.

20. Practice Problems

  1. A request body of 500 bytes goes through the same wrapping as in the first program. Work out the line time by hand and check it against the formula in the program. Hint: find the new Content-Length digit count.

  2. Change the phone's mask in the fourth program to /26. Which of the six destinations stay on the local network? Hint: a /26 covers 64 addresses starting at 192.168.29.0.

  3. In the third program, make the last segment the lost one. How many duplicate ACKs does the client send, and what does that say about fast retransmit? Hint: fast retransmit needs three later segments.

  4. Add a fifth experiment to the sixth program that flips a bit inside the TLS record only. Which check would catch it in real life? Hint: think about the tag.

21. Interview Questions

  • Which layer does a router work at, and a switch? A router works at layer 3 using IP addresses; a typical switch works at layer 2 using MAC addresses.

  • What changes at each hop, the frame or the packet? The frame is rebuilt on every link. The IP packet stays the same apart from the TTL and header checksum.

  • What is the difference between a layer 4 and a layer 7 load balancer? Layer 4 uses addresses and ports and forwards connections; layer 7 reads the HTTP request and can route by host or path.

  • Where does TLS sit? Between TCP and HTTP. Books put it at layer 6 or 5; it does encryption and session keys.

  • Ping works but the page does not load. What next? Test TCP to port 443, then the TLS handshake, then the HTTP response, then DNS and the logs.

  • What are MTU and MSS? MTU is the largest frame payload on a link, usually 1,500 bytes. MSS is the largest TCP data in a segment, usually 1,460 bytes on IPv4.

  • Why does the OSI model have seven layers when the internet uses four? OSI was designed as a reference first; TCP/IP grew from running code and merged the top three and the bottom two layers.

Summary

  • The OSI model splits communication into seven layers so each job, and each failure, has a name.

  • Encapsulation wraps the message in a header at every layer; small messages pay a large share in headers.

  • Routers read the layer 3 header and rebuild the frame at every hop; the IP packet survives.

  • The subnet mask decides whether the frame goes to the destination or to the gateway.

  • Layers check different things, and only an end-to-end check catches everything.

  • Troubleshoot bottom up; the first failing step names the layer.

Conclusion

The OSI model is a map, not the territory, but a map is what you want during an outage or a design review. Keep the seven names, remember what each one adds and checks, and use them to ask the next question. Continue with IP Address to see how layer 3 addressing really works, or return to the HLD course home to pick another topic.

Previous topic: Single Point of Failure. Next: IP Address.

References and further reading