Why most TCP servers are multi threaded and how to build one from scratch

  Рет қаралды 29,085

Arpit Bhayani

Arpit Bhayani

Күн бұрын

System Design for SDE-2 and above: arpitbhayani.me/masterclass
System Design for Beginners: arpitbhayani.me/sys-design
Redis Internals: arpitbhayani.me/redis
Build Your Own Redis / DNS / BitTorrent / SQLite - with CodeCrafters.
Sign up and get 40% off - app.codecrafters.io/join?via=...
In this video, I explained how to build a TCP server from scratch using raw sockets in a programming language like Go. I covered the basics of socket programming, system calls, handling multiple TCP connections, and processing HTTP requests. We created a simple server that listens to a port, accepts connections, reads requests, processes them, sends responses, and closes connections. However, the server we built could only handle one request at a time due to its single-threaded nature.
Recommended videos and playlists
If you liked this video, you will find the following videos and playlists helpful
System Design: • PostgreSQL connection ...
Designing Microservices: • Advantages of adopting...
Database Engineering: • How nested loop, hash,...
Concurrency In-depth: • How to write efficient...
Research paper dissections: • The Google File System...
Outage Dissections: • Dissecting GitHub Outa...
Hash Table Internals: • Internal Structure of ...
Bittorrent Internals: • Introduction to BitTor...
Things you will find amusing
Knowledge Base: arpitbhayani.me/knowledge-base
Bookshelf: arpitbhayani.me/bookshelf
Papershelf: arpitbhayani.me/papershelf
Other socials
I keep writing and sharing my practical experience and learnings every day, so if you resonate then follow along. I keep it no fluff.
LinkedIn: / arpitbhayani
Twitter: / arpit_bhayani
Weekly Newsletter: arpit.substack.com
Thank you for watching and supporting! it means a ton.
I am on a mission to bring out the best engineering stories from around the world and make you all fall in
love with engineering. If you resonate with this then follow along, I always keep it no-fluff.

Пікірлер: 85
@mitulvaghela906
@mitulvaghela906 Жыл бұрын
One of the best 28 minutes invested. Thanks Arpit!
@uditsankhadasariya5718
@uditsankhadasariya5718 Жыл бұрын
Hey Arpit, I've been following your channel for a while now and I've seen all your videos on system design and related concepts - I'm a huge fan! This video on building a TCP server is just amazing, and I love how it shows the practical side of things. It's so helpful to see real-world examples like this. I'd be thrilled if you could continue creating more content in this style. Keep up the fantastic work, and thanks for sharing your expertise with all of us! 🙌👩‍💻🚀
@SamarthKansalsammy
@SamarthKansalsammy Жыл бұрын
Damn, how can someone demystify the concept of "writing your own", which sounds quite scary, so beautifully. While watching this video i was glued to my computer screen. Thanks Arpit
@jayjay7333
@jayjay7333 Жыл бұрын
Love your content. May you never stop these quality videos.
@devashishrai1964
@devashishrai1964 Жыл бұрын
Thanks arpit this video is amazing. I kind of had an idea that spring or any framework does this but this video increased my clarity.
@lakshayasood2197
@lakshayasood2197 Жыл бұрын
this channel is a goldmine, how come i did not find it earlier. new saw anyone explaining TCP like this. Buonissimo!
@arbazadam3407
@arbazadam3407 9 ай бұрын
This one is gold. You have done a wonderful job to explain this. 💯
@nawazishkhan46
@nawazishkhan46 Жыл бұрын
Beautiful video, keep them coming
@MegaSurya1992
@MegaSurya1992 Жыл бұрын
I have never really thought, infinite for loop or loop is a valid usecase without knowing that every single day I am using it in interacting with each and every web server. Wonderful video... felt like my weekend was productive by watching this video, Thanks.
@ujjawal_
@ujjawal_ Жыл бұрын
amazing video, please make these types of videos with practical implementation 🎉
@imamansoni
@imamansoni 5 ай бұрын
Loved the explanation ❤. So simple amazing, Thanks
@deepakkothari2850
@deepakkothari2850 Жыл бұрын
This was quite informative and very well explained.
@8kumarssk
@8kumarssk Жыл бұрын
Arpit, Its a great and informative video. Really appreciate your efforts. It would have been good if you have included what is socket in tcp connection.
@santoshkpatro11
@santoshkpatro11 Жыл бұрын
This is gold 🎉.. Pure engineering
@dishantvashistha2038
@dishantvashistha2038 5 ай бұрын
Hey, Arpit . Amazing Explanation and description 🔥.
@yashashav_dk3766
@yashashav_dk3766 Жыл бұрын
We need more folks like you!
@viktoreidrien7110
@viktoreidrien7110 Жыл бұрын
hey man, great teacher i must say! superb video. thanks!!
@jayaramans7398
@jayaramans7398 Жыл бұрын
Thanks for detailed explanation. It will be helpful to share some sample web server on how they handle this
@nihshrey
@nihshrey 2 ай бұрын
What an amazing teacher you're, never enjoyed learning more. Extraordinarily simplified.
@AsliEngineering
@AsliEngineering 2 ай бұрын
Thank you @nihshrey!
@AleksandarT10
@AleksandarT10 Жыл бұрын
Great video, everyone should watch and should be aware of how multi threaded TCP web servers work
@krsingh.shubham
@krsingh.shubham 3 ай бұрын
I always had this curiosity in the head that how multiple connections are handled in prod but kept procrastinating untill today i watched this and went into dissecting them.
@varunpalsingh3822
@varunpalsingh3822 2 ай бұрын
Great explanation Arpit 🎉
@YashKhareDev
@YashKhareDev Ай бұрын
Best 28 Minutes spent on KZbin learning something! Thank you for such valuable content 🎉
@AsliEngineering
@AsliEngineering Ай бұрын
Thank you Yash!
@vikramragunathan6392
@vikramragunathan6392 Жыл бұрын
Very well explained. 👌
@sudhakarkamanboina
@sudhakarkamanboina Жыл бұрын
Very well explained
@debashisdeb472
@debashisdeb472 Жыл бұрын
This thing had intrigued me around 6 years back and I went ahead and implemented both single and multi threaded TCP sockets in Java :D
@daegu_1
@daegu_1 5 ай бұрын
TIME TO REWRITE IT IN RUST !!!!
@debashisdeb472
@debashisdeb472 4 ай бұрын
@@daegu_1 concepts are the same, so I don't think it will benefit me :)
@daegu_1
@daegu_1 4 ай бұрын
@@debashisdeb472 hahah yea
@ayushtripathi4514
@ayushtripathi4514 10 ай бұрын
omg!! it was just mindblowing
@vivekbhore5722
@vivekbhore5722 Жыл бұрын
pure quality content
@hemsagarpatel8992
@hemsagarpatel8992 10 ай бұрын
awsome video, got to know the internals of a webservers Thanks
@keshavb2896
@keshavb2896 Жыл бұрын
Amazing video as always!! , Can you please create a video on share nothing architecture like seastar framework...thanks a ton
@somnathroy102
@somnathroy102 7 ай бұрын
This is so freaking cool
@kchaitanya39
@kchaitanya39 7 ай бұрын
Maza aa gaya bhai
@J0Y22
@J0Y22 5 ай бұрын
great video
@jatinmanoj9523
@jatinmanoj9523 24 күн бұрын
This channel is a goldmine
@devpratap
@devpratap Жыл бұрын
Great video! Also how are you using handwritten notes in obsidian if I’m right?
@vikaskumar-oj2fr
@vikaskumar-oj2fr Ай бұрын
Man , you are a legend 👍
@vikrantverma7493
@vikrantverma7493 7 ай бұрын
There are very less useful videos on GoLang. I have started following you one month back and I can see how engineer should have thinking process. Also I am DevOps engineer and started learing golang just for my interest. Thank you for this video. Keep it up.
@gurupreetsingh8347
@gurupreetsingh8347 Жыл бұрын
Hey really good explanation, bro yeh servers ke internal source code milte kahan se hai ? Which site or content you prefer?
@aqilaghamirzayev8189
@aqilaghamirzayev8189 5 ай бұрын
Thank you. Can you please make the same video for the reactive web server?
@TheNayanava
@TheNayanava Жыл бұрын
awesome video!! I was expecting you to talk about I/O multiplexing as well when you were talking about multi-threaded servers, and indeed you did in the 24th minute!!
@AsliEngineering
@AsliEngineering Жыл бұрын
yeah. IO Multiplexing is great; it just minimises synchronization and threading overheads. Unfortunately could not go in depth of implementation, given I cover it in my Redis course. Had to draw the line. Glad you still found the video interesting :)
@TheNayanava
@TheNayanava Жыл бұрын
@@AsliEngineering loved it!!! 👏👏 actually I was aware of I/O multiplexing when we used RedisStackExchange library in one of the projects.. but after watching your video, I really did a deeper dive to understand how things work under the hood!
@AsliEngineering
@AsliEngineering Жыл бұрын
@@TheNayanava engineering curiosity for the win 🙌
@TheNayanava
@TheNayanava Жыл бұрын
@@AsliEngineering your videos are the second best thing on youtube after Hussein Nasser's videos. Not comparing, just putting in chronological order. 😁😁
@AsliEngineering
@AsliEngineering Жыл бұрын
@@TheNayanava Hussein is next level. I really wish I could go as deep as him. He actually pointed into Postgres source code. That's commendable, given how complex the codebase is.
@tejasarlimatti8420
@tejasarlimatti8420 Жыл бұрын
bhai legend hai tu
@anshkumargarhewal8582
@anshkumargarhewal8582 Жыл бұрын
Hello Bhaiya love this content, btw can you please make one video on OSI model, Please 🥺
@shishirchaurasiya7374
@shishirchaurasiya7374 9 ай бұрын
Arpit sir just a small doubt I have here is that as if you are saying that the code is single threaded server, because of which multiple requests are not able to process at the same time they are waiting for 1 process to complete, my question is these process which has been started, as they are waiting you mentioned but there is no such queue in which they can store, so how currently these values which are not yet executed are getting stored basically their internal workings I am concerned about, if there is no data structure used then why the process is not leading to crash of the applications or Is GO Language is handling these internal working ?
@kritibindra4232
@kritibindra4232 11 ай бұрын
Hey Arpit, awesome video that explains the working of a server. Just curios to know 1 thing. In your example from the client side you made 2 requests almost simultaneously and while 1 connection got accepted, what actually happens to the other client request till the server is busy? Since it kept on waiting for the server to get freed up…do we have some queue that keeps track of all requests that has been made to the port? Or internally do we keep on trying from the client side till some TTL window where if it gets crossed the client will close the conn from its side saying server took too long to respond or something like that?
@bishwashpokhrel8779
@bishwashpokhrel8779 10 ай бұрын
Thats what backlog queues are for, on starting a socket connection you can determine how many connections can wait in the backlog. I think when the queue is full the connections are simply discarded.
@Akz77977
@Akz77977 Жыл бұрын
Hey Aprit, amazing videos, i have started watching your videos recently. Just a suggestion as a viewer, could you declutter notes that you use for teaching, only diagrams and one words are enough, you are already explaning everything on top of it. It feels redundant information on the notes and blocks the important information if you would have written.
@ujjwalgupta3445
@ujjwalgupta3445 9 ай бұрын
Wow!!
@abhishekvrshny
@abhishekvrshny Жыл бұрын
Nginx is not multithreaded. It is multi-process (1 process per core) and uses asynchronous I/O (with epoll) where a single process can accept and process multiple connections and requests.
@AsliEngineering
@AsliEngineering Жыл бұрын
Ohhh. Thanks for correcting. I knew Redis did it, but Nginx was new. Thanks a ton. Really appreciate it.
@jainamshah3691
@jainamshah3691 9 ай бұрын
Hii Arpitbhai, Understood how multi threaded web server works. Still I have one doubt how listen and accept works. Like lets say we invoked the listen on some particular port how the process is listening like how it actually listens internally that as soon as client connects it accepts the request and how read write actually works. I know the concept of pipe but as far as I know its for local processes only. I hope you got my doubt.. Thanks for the nice explanation.
@rohitagarwal4731
@rohitagarwal4731 4 ай бұрын
bhaiya if i want to include a multithreaded web server project in my resume , and want a live link like other projects , how can i deploy it ?
@raviprakashbajpai196
@raviprakashbajpai196 9 ай бұрын
How many connections a server can handle concurrently? I guess conn object return by listener.accept will be different for each curl request ? or that conn object is a shared resource between threads.
@siddharthsingh7281
@siddharthsingh7281 Жыл бұрын
More like this I did this first time but one question since node is single threaded how does it handle such connections?
@siddhantchavan1370
@siddhantchavan1370 10 ай бұрын
node isnt single threaded, it has internal worker threads. Read libuv library for more info!!
@codecuptips
@codecuptips 5 ай бұрын
Can I achieve this with nodes
@yogeshsherawat
@yogeshsherawat Жыл бұрын
If number of concurrent requests are more than the number of threads present in thread pool, then the extra requests will have increased response time or the request would get dropped?
@AsliEngineering
@AsliEngineering Жыл бұрын
queued and then dopped
@alphacoder3822
@alphacoder3822 10 ай бұрын
Engineering is buetyful
@sarveshwarsinghal5916
@sarveshwarsinghal5916 Жыл бұрын
Hi, how consistency is maintained across multiple threads? assume we've written a class that has a static counter which gets increased after every call. In a single threaded scenario the value of counter would remain consistent after n calls are made. But how can we make sure this is followed in multi-threaded servers? Assume the code you've written has a global counter variable and this variable gets increased in the 'do' function. Now in multi-threaded environment how we can make sure that the state of counter is correct after n parallel calls are made.
@AsliEngineering
@AsliEngineering Жыл бұрын
Optimistic locking, pessimistic locking, and atomic updates.
@sarveshwarsinghal5916
@sarveshwarsinghal5916 Жыл бұрын
@@AsliEngineering okay. How is this implemented in production? Let's say I've spring boot local server, and there's a static variable in a different class that I want to a update. I've a REST controller exposed via get/post. Now in my local I'm not creating multiple threads, spring boot automatically serve multiple requests. So how to apply lock in this scenario, and where to put locking code. Thanks
@AsliEngineering
@AsliEngineering Жыл бұрын
@@sarveshwarsinghal5916 this Friday I will put out a video on it. Already recorded.
@sarveshwarsinghal5916
@sarveshwarsinghal5916 Жыл бұрын
@@AsliEngineering thanks. Also could you recommend any good engineering blog or article related to this.
@foobar69
@foobar69 Жыл бұрын
masiha h re tum bro... ek request h bro, kyoki maine kabhi kaam nhi Kiya h distributed systems me to kind of imposter wala feeling aata hai apply karne me. thoda kuch bta do bro k ek project agar scratch se banate ho to kya expected hota h ek 5-6 yr experienced bande se. please 🙏🙏 8
@abhijitkrao283
@abhijitkrao283 Жыл бұрын
What's your development environment and laptop type?
@AsliEngineering
@AsliEngineering Жыл бұрын
Laptop: Lenovo Ideapad 8 GB RAM AMD Processor. IDE is plain and simple VS Code. Nothing fancy.
@myslates2854
@myslates2854 Жыл бұрын
@@AsliEngineering Which VI plugin's you use, as the one by default in VScode is very sluggish. Do you have any cheatsheet for the VI which you use frequently.
@codecuptips
@codecuptips 5 ай бұрын
You made it asynchronous..
@ashiktm5631
@ashiktm5631 9 ай бұрын
In nodejs express also same thing happens right?
@AsliEngineering
@AsliEngineering 9 ай бұрын
No. that's async io.
@salman0ansari
@salman0ansari 10 ай бұрын
4:05 😂
@AsliEngineering
@AsliEngineering 10 ай бұрын
Unfiltered me 🙈
@Lokeshsanapalli1729
@Lokeshsanapalli1729 8 ай бұрын
I opened the video to see the implementation of multi-threaded tcp server and the challenges of it. But, what implemented here is just a TCP server 😢
@AsliEngineering
@AsliEngineering 8 ай бұрын
What I implemented is a multi-threaded TCP server. So long as challenges are concerned, they are exactly what you'd face when you have multiple threads - synchronization.
Optimistic Locking - What, When, Why, and How?
16:34
Arpit Bhayani
Рет қаралды 12 М.
How To Build A Custom TCP Server In Golang!?
19:32
Anthony GG
Рет қаралды 24 М.
Must-have gadget for every toilet! 🤩 #gadget
00:27
GiGaZoom
Рет қаралды 11 МЛН
КАРМАНЧИК 2 СЕЗОН 7 СЕРИЯ ФИНАЛ
21:37
Inter Production
Рет қаралды 368 М.
Жайдарман | Туған күн 2024 | Алматы
2:22:55
Jaidarman OFFICIAL / JCI
Рет қаралды 1,3 МЛН
Everything you need to know about REST
26:20
Arpit Bhayani
Рет қаралды 23 М.
Inside Juspay: A Sneak Peek of Our Tech, Systems & Culture
11:45
How DNS really works and how it scales infinitely?
16:35
Arpit Bhayani
Рет қаралды 20 М.
Peeking into assembly code to understand why count++ is not atomic
14:12
Razorpay's Journey to Microservices w/ Arjun | Ep 1
49:48
Arpit Bhayani
Рет қаралды 53 М.
How to write a multithreaded server in C (threads, sockets)
14:30
Jacob Sorber
Рет қаралды 130 М.
Everything you need to know about CockroachDB w/ Ben Darnell | Ep 6
1:30:03
What is a Protocol? (Deepdive)
18:14
LiveOverflow
Рет қаралды 158 М.
Урна с айфонами!
0:30
По ту сторону Гугла
Рет қаралды 7 МЛН
YOTAPHONE 2 - СПУСТЯ 10 ЛЕТ
15:13
ЗЕ МАККЕРС
Рет қаралды 117 М.
APPLE совершила РЕВОЛЮЦИЮ!
0:39
ÉЖИ АКСЁНОВ
Рет қаралды 4,3 МЛН
iPhone 12 socket cleaning #fixit
0:30
Tamar DB (mt)
Рет қаралды 54 МЛН