15 ms·
What developers should know about TCP
- commandlinefan 7y agoWhen I first started working with computer networks, I just thought of TCP/IP as "low-level stuff" and I focused instead on the higher level stuff. After I kept running into incomprehensible errors seemingly over and over again, I finally broke down and picked up a copy of Richard Steven's "TCP/IP Illustrated". Hands down, the best investment in time I've ever made. If you deal with distributed systems (hint, you do), you need to understand how they actually work.
- rb808 7y agoGreat I thought I'll take a look. Three volumes each over 1000 pages? Any other suggestions? Did you mean all 3 books?
- commandlinefan 7y agoHehe - I did end up reading all 3, and enjoyed them all, but I'd say I got 90% of the value from volume 1. Volume 2 walks through the BSD implementation of TCP/IP, which is fascinating, but way more detail than you'd ever need to know, and volume 3 goes off into some esoteric topics that seemed promising at the time but mostly ended up being abandoned (along with a brief discussion of HTTP as it was around the 90's). If you're going to read it, though, find a used copy of the original Stevens' first edition, not that terrible desecrated second edition.
- Bootvis 7y agoWhat is wrong with the second edition?
- commandlinefan 7y agoIt was rewritten by a different author (the original author, Richard Stevens, died in a car accident in the late 90's). I guess the new guy tried his best, but he just doesn't have the writing skill that Stevens had.
- deleted 7y ago[deleted]
- tenant 7y agoDepressing, isn't it? There are so many books that I probably should read about almost any number of topics that, in my work, I "touch on".
- rb808 7y agoLol I'll probably buy it and put on my bookshelf with all the others.
- irrational 7y agoI have books that I purchased decades ago like this that are still languishing on my bookshelf.
- hilem 7y agoNot OP but the first volume is the one that's cited frequently and the only one of the series I believe to have a second edition.
- kevstev 7y agoJust read the first one- it reads more like a novel than a textbook IMHO, though I may be biased- I have always been fascinated by networks and when I was coming of age this was the "high tech" of the time- I used to read RFCs for fun (I highly recommend this as well if you want to dig a little deeper- Jon Postel's are great reads). This is one of the best written textbooks, if not the best, I have ever read.
- rramadass 7y agoNo. They are huge because they are highly detailed and nitpicky. I suggest the following for understanding Networking and TCP/IP; * An Engineering Approach to Computer Networking: ATM Networks, the Internet, and the Telephone Network by S.Keshav * TCP/IP Illustrated Vol -I by Richard Stevens (any edition will do). * Effective TCP/IP programming by Jon Snader.
- c0nsumer 7y agoA lot of benefit that I add in my day job is bridging the gap between high level folks (OS people) and what's-actually-happening-on-the-wire. While so, so, so much of this is rarely the network, knowing how to look under the covers and see what's actually hitting the wire (versus what the API call asked for) leads to far, far faster resolution of problems. It's frustrating to me that so many people see this as a mystery of "knowing networking" when it's really just basic protocol analysis.
- non-entity 7y agoIs this still a reccomend book? I was looking for a good TCP/IP reference book, but many seemed rather old. Of course, I imagine protocols like that dont get modified too much.
- commandlinefan 7y agoWell, it's definitely out of date: the first edition predates even IPv6 (and the second edition is awful, don't buy it). Still, the way it's laid out is so well done that once you understand how TCP/IP worked in the mid-90's, you'll easily be able to work out the evolution of it since on your own. It's a shame there's no better up-to-date book, but Stevens was one-of-a-kind. The Comer book isn't bad (but it's not really good, either), and the Kurose & Ross book is less not bad (and more not good), but even though both are more modern, I'd still recommend TCP/IP Illustrated to really understand what's going on in the network stack.
- travmatt 7y agoI just finished Kurose’ “Computer Networking: A Top-Down Approach” and I’d recommend it.
- outworlder 7y ago> I focused instead on the higher level stuff. That's fine. But every developer should have a basic understanding of networking. But that can also be dangerous. I still have people in the company who swear you can't have more than 65k incoming connections to a machine, because "that's how many ports there are". Don't get me started on all the misconceptions on TCP_TW_REUSE AND TCP_TW_RECYCLE. Lengthy discussions because apparently "TIME_WAIT is bad and uses up ports! "(see also, 65k). For context, these are servers, with multiple clients, from different source IPs.
- 29athrowaway 7y agoThe RFC is useful as well. https://tools.ietf.org/html/rfc793 https://tools.ietf.org/html/rfc793 TCP state machine diagrams can be useful too.
- Matthias247 7y agoWhat they mostly should know: TCP provides a bidirectional stream of bytes on the application level. It does NOT provide a stream of packets. That means whatever you pass to a send() call is not necessarily the same amount of data the receiver will observe in a single read() call. You might get more or less bytes, since the transport layer is free to buffer and to fragment data. I have seen the assumption of TCP having packet boundaries on application level being made too often - typically in stackoverflow questions like: „I don’t receive all data. Is my OS/library broken?“
- fenwick67 7y agoThis probably bites lots of newbies, since when you're just sending traffic over localhost, the send()s and read()s tend to line up.
- yjftsjthsd-h 7y agoI have often wished for an "unhelpful testing environment" of sorts, to deal with these things before they get out of hand. It would feature a compiler that had creatively different interpretations of undefined behaviors, randomly compile against glibc and musl, have a base OS lovingly crafted from Ubuntu, but with most coreutils replaced with busybox and/or BSD versions. And, now, I suppose, it would have a customized network stack (kernel module?) that would randomly reorder/drop/duplicate packets, randomly reselect MTU on every boot, or maybe just randomly fragments things regardless of MTU. Ideally it would come with a FAQ of "my program broke on X; what did I do wrong?". The idea being that if your software is actually written to relevant standards, and actually handles things properly outside the golden path, then it should still work fine. If, however, you accidentally did something implementation-defined, or that only worked by coincidence, this system will break it.
- Matthias247 7y agoI created such an environment for my unit-tests: Wrapping TCP sockets in a stream which only accepts 1 byte at a time in both directions and returns EAGAIN on every second read provides an easy way to make sure the code on top of the socket does perform all the correct retries. That will most likely not help newcomers which directly write their code agains the OS socket. But once you get a better understanding of the topic and start adding tests to your codebase it's rather easy to add.
- bsamuels 7y agoWhy doesn't the congestion control part of TCP prevent buffer bloat[1]? Is it because ISP throttling of the internet connection doesn't touch the TCP packets themselves? I recently started doing off-site backups, which requires my entire internet uplink to be used for uploading said backups for about a week at a time. The internet basically becomes unusable because all the packets end up in a buffer on the router and latency spikes to 5000ms. [1] https://www.bufferbloat.net/projects/bloat/wiki/What_can_I_do_about_Bufferbloat/ https://www.bufferbloat.net/projects/bloat/wiki/What_can_I_d...
- jeffbee 7y agoIf there is a huge FIFO queue on your router, the rate-finding algorithms associated with TCP will be forced to conclude that the RTT to your site is enormous. They may try to open the window to compensate, but here's a fun fact: most operating system default settings are insufficient to utilize very high bandwidth-delay products. If you want to send a 1gbps flow across an 80ms distance on Linux, you'll need to change some parameters with sysctl before it will work. If your apparent RTT is 5000ms, the flow you can get will be reduced in proportion. In any case, the solution to bufferbloat is queue discipline, not congestion control.
- jfkebwjsbx 7y agoUp to what speeds/latencies are the default sysctl parameters alright? Is there any easy way to know whether you are getting hit by this? Nowadays many people is getting 1 Gbps links at home! What do you mean by queue discipline?
- jeffbee 7y agoYou know, the worst part is that Linux sets the maximum receive window size at boot time depending on how much memory the system contains, ensuring that it's never quite right. On this machine, with 32GB of main memory, it defaults to 6291456 bytes.
- 7y ago
- jeffbee 7y agoJust enough information to be dangerous? Article attributes behaviors of loss-based congestion control schemes like Reno and Cubic to TCP itself. In practice, the congestion control scheme is not really part of the protocol (there is, for example, BBR). There's also ECN, showing that loss is not the only way to discover congestion.
- convolvatron 7y agothe RTT discussion was a little misleading. its true that slow start rates are entirely dependent on RTT...but eventually the sawtooth should reach the same steady state. there is work that shows that higher RTT connection do statistically suffer a smaller fair share, but that's a subtler if related issue. actually, I really wish the author would have shown the sawtooth.
- toast0 7y agoAt some point, with increasing bandwidth and increasing RTT, you end up with your effective bandwidth capped by receive windows and/or send buffers. Cross country high def video might not be quite enough to hit that, but intercontinental high def video would be. Being closer means faster initial 'slow start', but also faster 'slow start' on congestion, which is why you get a bigger share.
- convolvatron 7y agosure. but thats really just a window being under the bandwidth delay product. the discussion makes it seem like you suffer an outright linear performance hit
- deleted 7y ago[deleted]
- crazygringo 7y ago> But what about large files, such as videos? Surely there is a latency penalty for receiving the first byte, but shouldn’t it be smooth sailing after that? So the articles (unstated) conclusion seems to be that, as long as there isn't network congestion, it is smooth sailing after that. But that congestion reduces bandwidth. But of course, that applies just as much to a national backbone as to last-mile. So I'm curious: where does most packet loss occur? Is it last-mile, at your ISP, or along major backbones? Because that has major implications as to whether caching video content closer to users actually results in higher-quality video (e.g. supporting 1080p instead of 720p) or not.
- boryas 7y ago> where does most packet loss occur Here's an interesting paper from SIGCOMM (it won best paper at the conference in 2018, FWIW) that attempts to figure out what links are congested without direct access to ISP networks: https://www.caida.org/publications/papers/2018/inferring_persistent_interdomain_congestion/inferring_persistent_interdomain_congestion.pdf https://www.caida.org/publications/papers/2018/inferring_per...
- z3t4 7y agoIve been debugging packet loss issues lately and they did all occur in the datacenter. For backbones and network exhanges they move so much traffic already that things like everyone working remote only increases traffic by a few percent, and they have a lot of over capacity in order to handle spikes or when a new game is released and everyone downloads it at the same time. So yes it would really help to have more decentralisation. Like putting the content closer to the user.
- resca79 7y agoI loved this area when I was at university. At the end of Computer Networking course I brought a project on based on https://www.isi.edu/nsnam/ns/ https://www.isi.edu/nsnam/ns/ It was really fun expecially because it allows you to understand better all networking layers. I did some tests about network topology to minimize lost tcp packs as possible, given different network traffics
- deleted 7y ago[deleted]
- citrin_ru 7y agoA very important point every develeper should know: successful write(2) syscall doesn't not grantee that the data received by a remote application. TCP is described as a protocol which grantees packet delivery and this often misleading. write(2) syscall returned without a error means that data has been placed in OS kernel buffer. OS kernel then will try to send it to a remote host. If couple packet will be lost it's not a problem - kernel will retry a few times. But if power will be lost shortly after a write, data may never hit the wire. Then there is possibility that network link will be broken for a long time. OS will retry, but for a limited time and then will give up. Also remote host can crash at any time before remote application actually will read the data. So if you need reliable delivery you need acknowledgement on application protocol level despite the fact that TCP already have acknowledgements.
- ex3ndr 7y agoThe biggest issue with TCP is that it can randomly freeze and you have to restart it in pretty much any network. You CAN NOT rely on socket closing on any side, you have to maintain connection by yourself. I am super puzzled why something like websockets not solving this problem, simple heartbeat could solve the problem, but no one implements it.
- gsich 7y agoYou can use keepalives at the protocol (TCP) level.
- ex3ndr 7y agoIn 99% of cases you don't have an api to do so.
- gsich 7y agoThat's not the protocols fault. Besides, the OS usually does this, not your program. SO_KEEPALIVE is available on all relevant OS.
- Sami_Lehtinen 7y agoDefault keepalive time of two hours is also quite long, in some situations, where you would expect to get the notification just a bit faster.
- gsich 7y agoYes, default values are not sane for most connections.
- ex3ndr 7y agoGood luck access this from browser.
- 7y ago
- freefriedrice 7y agoEDIT: Sure wish I could delete this post. Wait, this isn't TCP, this is protocol level above TCP, right? TCP doesn't shape traffic by itself through rate limiting and congestion analysis, does it? I thought the layer above it used TCP to send/receive the buffer size, and that has nothing to do with TCP. Am I wrong?
- zwkrt 7y agoYou are wrong! Obviously the application layer on top of TCP could be the bottleneck, but TCP itself has mechanisms to ensure traffic is flowing as fast and as smoothly as possible. Look up "TCP Flow control" and "TCP Congestion Control"
- scott_s 7y agoTCP definitely does congestion control itself: https://en.wikipedia.org/wiki/TCP_congestion_control https://en.wikipedia.org/wiki/TCP_congestion_control
- vinay_ys 7y agoSingle biggest TCP issue I have had to debug and fix numerous times is about not doing connection reuse properly leading to tcp port exhaustion and causing seemly random delays causing timeout failures at higher level protocols, usually http. This one single issue has taken down multi-billion dollar production systems. So, I hope people learn to check their http client/server implementations to have proper connection handling. Client should have a thoughtfully sized bounded connection pool with reasonably large idle timeout. It shouldn't close the connection after every application request (say, http request). There shouldn't be sockets in TIME_WAIT state accumulating at the client end. Server should accept thoughtfully limited number of connections per client. Server should never close the connection except when it is shutting down. There should be tcp keepalive messages to keep the connection alive with intermediate hop stateful firewalls (connection tracking table entries in firewalls expire when the connection is idle for too long) and to detect stale connections and re-establish them. All of these things can be verified by analyzing at a packet capture. You can get a manageable sized pcap file by filtering on client/server ip/port-range pairs for at least 330 seconds. Knowing tools to understand/debug tcp issues is an essential skill. sock stat command - ss, wireshark/tshark with Lua scripting is super useful. Knowing higher level application protocols like TLS and http is essential too.
- dblohm7 7y agoThis reminds me of an issue I had to debug over a decade ago. Our product had its own protocol written atop TCP, but its handshake was written in a way such that it was much slower than it should have been due to delays caused by the Nagle algorithm. Turning on TCP_NODELAY was a quick-n-dirty fix, but the real fix was to rewrite the handshake to be more compatible with the inner workings of TCP.
- duxup 7y agoWhen I used to do networking tech support for some networking equipment the guy's who sat next to me supported the load balancer product. I swear a high percentage of their calls were questions about how the load balancer wasn't working and sending all the traffic to one server and then after some investigation we discover all traffic is in fact directed to that lone server... because the client code has the IP of that server hard coded. A tedious discussion would then ensue about how that is not how to do it. The next week? Same angry call... Partly that is what inspired my decision to change careers. "Man if these developers can't figure out basic networking, maybe I could be a developer...?"
- joana035 7y agoI have the same tedious discussion every time a new box is replaced. It goes in the lines of "no, changing a box will not make your application behave differently, fix your dawn thing".
- Jonnax 7y agoSo the video example here, does it indicate that UDP is more suited for video transmission? Does http3 fix this?
- rramadass 7y agoThe article just explains some details but not the main concept behind TCP i.e. TCP is a connection and stream based protocol of bytes. All it takes is to explain the idea of Counting bytes with a Sliding Window and almost everybody will "get" TCP. Never talk about packets.
- mitchs 7y agoSomething worth knowing: TCP checksums should not be relied upon. If you aren't using TLS, your application needs to do its own checksums. A 16 bit 1's complement sum over a packet is not sufficient, especially given modern switch ASIC design. They take really fast signals off the fiber and turn them into slow moving, parallel signals within the ASIC. Often these signal buses are nice even numbers of bytes wide, 204 in this example. When there is something flawed in the chip in the slower moving internal pipeline, it will hit the same bit position every 204 bytes. If it is borked enough to flip two bits within the packet, those flips will be in the same bit position a multiple of 204 bytes away, meaning the same bit position in the 1's complement checksum. If one flips up, and the other flips down, it passes! In my case it ended up corrupting data in a BGP session's TCP stream, executing the world's most confusing route hijack in our network.
- salawat 7y agoAh... Network hardware troubleshooting. Truly, it separates the frustration tolerant from the frustration intolerant. If not because of the challenge of having to take into account things mist programmer's treat as invisible, but because it usually involves at least one conversation with another network provider to check their stuff; which generally leads to the most passive aggressive dodging of blame until you get that one operator who's one goal in life is to keep the Internet running correctly.
- kaliszad 7y agoI signed up to thank you for this insight. It's the kind of thing you would eventually find out on your own too but having read it somewhere in words saves time when something wonky happens somewhere and the data supports the conclusion. There are people who would swear by the chips/ hardware not being an issue (which is usually correct but not always). I wonder, why would somebody use 204 bytes -> 1632 bits, why not less (why not more for e.g. jumbo frames). Is there some data sheet / source that you would recommend?
- dharmab 7y agoOne of our favorite troubleshooting stories was "3% of TLS connections fail on this particular frontend IP address. HTTP works." Turned out our cloud provider's networking gear had a bug that disabled ECC and there was a bit flip happening. Convincing the provider's support that we had found faulty hardware in their datacenter was an interesting journey.
- agnivade 7y agoUnrelated: does anybody know the tool used to make those diagrams ?
- abhorrence 7y agoIt looks like excalidraw.
- agnivade 7y agoYeah, it's so good and it's open-source !
- emmanueloga_ 7y agoBack in the day I remember learning about TCP and other systems subjects through Beej Guides! [1]. Is there other material recommended to review network programming? I know about the Stevens' books but they look so bulky and dry... 1: https://beej.us/guide/ https://beej.us/guide/