HOW[NOT]TO Write TCP-based
Network Applications




                             Artyom Gavrichenkov
                                            1/x
Based on a True Story
• NOT AN AD!
• Qrator: distributed network
   ●  Custom TCP/IP at the bottom
   ●  Custom management protocol at the top
   ●  Interacting with plenty of Web servers and Web browsers
      on a daily basis
    ●   2 years of continuous debug^W Product ImprovementTM




                                                                2
Issue #1

• Message delivery is unreliable in TCP.
Issue #1

• Message delivery is unreliable in TCP: there's no
  estimation on when (and if) the message will arrive
  at all
• Timeouts!
• Limit all resources, including time
• No action is itself an action
Timeouts

• Between recvfrom()
• Between requests
• Request timeout
• Lifetime of a session
• Lifetime of %OBJECTNAME%
• Long polling may be a bad idea
Ex. 1

• Slowloris (Apache): DoS
    ●
      (not distributed, just denial of service)
• Slow HTTP POST
    ●
      Apache, IIS, Lighttpd: DoS
    ●
        Nginx: DDoS with a botnet
Ex. 2

12 rpm AJAX page update
 ● Backup script switched the server off
Dumb Ways To Die: How Not To Write TCP-based Network Applications
Content-Length
–   Limit resources for all actions
–   Custom protocol should define limits on the
    input length
errno(3)
–   The connection may be closed for no good
    reason
–   Check errno after recvfrom(), sendto(), etc.
     ●   ENOMEM
     ●   ECONNRESET
     ●   EANYTHING
Ex. 3
●   Internet Explorer: ECONNRESET means
    successful connection termination
    –   Download status is being ignored
    –   Content-Length is being ignored
Memory limits
–   Resource limits:
     ●
         Maximum
          – ENOMEM
     ●
         Minimum
          – idle wait → ECONNRESET
Ex. 4
–   DNS TTL
    ●
        Too big: days of downtime (continuous)
    ●
        Too small: days of downtime (total)
Latency
–   3-Way Handshake takes time
–   Do implement persistent connections!
    ●
        Do it from the very beginning
They haven't listened to me!
●
    TCP
    –   T/TCP
●
    HTTP/1.0
    –   HTTP/1.1
Optimization
–   Measure!
–   Profile!
–   Emulate packet loss!
Optimization
–   Text-based protocols are convenient to debug
     ●
       And you will debug
        – Maybe even in production
–   Making use of binary protocols is often a
    premature optimization
     ●
         BSON, Google Protocol Buffers
Optimization
●
    TCP socket options:
    –   TCP_NODELAY: disables Nagle's algorithm
        ●
           Speedup with small portions of data
    –   TCP_CORK (Linux): multiple portions of data
        in a single TCP segment
    –   "socket corking"
Optimization
●
    TCP stack options:
    –   Linux: /proc/sys/net/**
         ●
             net.ipv4.tcp_fin_timeout
         ●
             net.ipv4.tcp_{,r,w}mem
         ●
             net.core.{r,w}mem_max
    –   Windows:
        HKLMSystemCurrentControlSetServicesTcpipParameters
IPv6

●   Accidental IPv6 deployment
• SO_REUSEADDR
• sendfile(2)
• select(2)/poll(2)/epoll(7)
• {n,h}to{n,h}{s,l}()
• int64_t vs long




                               21
This is it!
Artyom Gavrichenkov <ximaera@highloadlab.com>

More Related Content

PDF
DB Latency Using DRAM + PMem in App Direct & Memory Modes
PDF
Vanquishing Latency Outliers in the Lightbits LightOS Software Defined Storag...
PDF
High-Performance Networking Using eBPF, XDP, and io_uring
PDF
Tempesta FW - Framework и Firewall для WAF и DDoS mitigation, Александр Крижа...
PDF
Practical SystemTAP basics: Perl memory profiling
PDF
Let’s Fix Logging Once and for All
PDF
Ltsp talk
PDF
An Introduction to the Formalised Memory Model for Linux Kernel
DB Latency Using DRAM + PMem in App Direct & Memory Modes
Vanquishing Latency Outliers in the Lightbits LightOS Software Defined Storag...
High-Performance Networking Using eBPF, XDP, and io_uring
Tempesta FW - Framework и Firewall для WAF и DDoS mitigation, Александр Крижа...
Practical SystemTAP basics: Perl memory profiling
Let’s Fix Logging Once and for All
Ltsp talk
An Introduction to the Formalised Memory Model for Linux Kernel

What's hot (20)

PDF
Understanding of linux kernel memory model
PDF
Ltsp Slide
PDF
Rust Is Safe. But Is It Fast?
PDF
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
PDF
Where Did All These Cycles Go?
PDF
Rust, Wright's Law, and the Future of Low-Latency Systems
PDF
GCMA: Guaranteed Contiguous Memory Allocator
PDF
Cloud Compt
PDF
Linux Kernel Memory Model
PDF
3 technical-dns-workshop-day2
PDF
Glomosim introduction
PDF
SELinux by Example
PDF
gcma: guaranteed contiguous memory allocator
PDF
Fundamental of Shell Programming
PPT
Glomosim
PDF
Go performance tooling
PPTX
Analysis of an exploited npm package
PDF
Introduction to ns2
PDF
Intro to Packet Analysis - pfSense Hangout May 2014
Understanding of linux kernel memory model
Ltsp Slide
Rust Is Safe. But Is It Fast?
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
Where Did All These Cycles Go?
Rust, Wright's Law, and the Future of Low-Latency Systems
GCMA: Guaranteed Contiguous Memory Allocator
Cloud Compt
Linux Kernel Memory Model
3 technical-dns-workshop-day2
Glomosim introduction
SELinux by Example
gcma: guaranteed contiguous memory allocator
Fundamental of Shell Programming
Glomosim
Go performance tooling
Analysis of an exploited npm package
Introduction to ns2
Intro to Packet Analysis - pfSense Hangout May 2014
Ad

Viewers also liked (20)

PDF
Александр Крижановский, NatSys Lab
PDF
Game of BGP
 
PDF
Циклы маршрутизации на междоменном сетевом уровне
 
POTX
Архитектура центра очистки трафика (ЦОТ): решения уровня оператора связи и ко...
 
PDF
Erlang railsclub - 1
PDF
Порядок преодоления болота на маршруте: как не надо писать приложения, основа...
 
PDF
DDoS: Practical Survival Guide
 
KEY
Актуальное состояние вещания видео в интернете
PDF
Тандемные DDoS-атаки / Проблематика уязвимостей в спецификации TCP/IP (фундам...
 
PDF
Некоторые аспекты влияния сходимости протокола BGP на доступность сетевых рес...
 
PDF
BGP Route Stability
 
PDF
Влияние сетевых аномалий на доступность ресурсов
 
PDF
Detecting Autonomous Systems Relationships
 
PPTX
Beyond the botnet
 
PPTX
DDоS: Практическое руководство к выживанию. (Часть 2: Работа над ошибками)
 
PDF
DDoS-атаки в 2011 году: характер и тенденции
 
PPTX
Russian Internet Core: политики маршрутизации
 
PPTX
Динамика DDoS-атак в России
 
PDF
UDP Amplifiers на примере DNS и способы противодействия
PDF
Pulsedb — система хранения временных рядов
Александр Крижановский, NatSys Lab
Game of BGP
 
Циклы маршрутизации на междоменном сетевом уровне
 
Архитектура центра очистки трафика (ЦОТ): решения уровня оператора связи и ко...
 
Erlang railsclub - 1
Порядок преодоления болота на маршруте: как не надо писать приложения, основа...
 
DDoS: Practical Survival Guide
 
Актуальное состояние вещания видео в интернете
Тандемные DDoS-атаки / Проблематика уязвимостей в спецификации TCP/IP (фундам...
 
Некоторые аспекты влияния сходимости протокола BGP на доступность сетевых рес...
 
BGP Route Stability
 
Влияние сетевых аномалий на доступность ресурсов
 
Detecting Autonomous Systems Relationships
 
Beyond the botnet
 
DDоS: Практическое руководство к выживанию. (Часть 2: Работа над ошибками)
 
DDoS-атаки в 2011 году: характер и тенденции
 
Russian Internet Core: политики маршрутизации
 
Динамика DDoS-атак в России
 
UDP Amplifiers на примере DNS и способы противодействия
Pulsedb — система хранения временных рядов
Ad

Similar to Dumb Ways To Die: How Not To Write TCP-based Network Applications (20)

PDF
High perf-networking
PDF
Computer network (10)
PPTX
High performance browser networking ch1,2,3
PDF
Computer network (7)
PDF
PPTX
Network protocols and vulnerabilities
PDF
Application layer
PDF
Osi model
PDF
presentationphysicallyer.pdf talked about computer networks
PDF
Real-time in the real world: DIRT in production
PPT
Np unit iv ii
PDF
Ismail TCP IP.pdf
PDF
Ismail TCP IP.pdf
PPT
tcpip.ppt
PPT
Introduction to TCP / IP in networking Technology
PPT
tcpip.ppt protocol power point presentation
PPT
tcpip.ppt
PPT
PPT
tcpip.ppt
PPT
High perf-networking
Computer network (10)
High performance browser networking ch1,2,3
Computer network (7)
Network protocols and vulnerabilities
Application layer
Osi model
presentationphysicallyer.pdf talked about computer networks
Real-time in the real world: DIRT in production
Np unit iv ii
Ismail TCP IP.pdf
Ismail TCP IP.pdf
tcpip.ppt
Introduction to TCP / IP in networking Technology
tcpip.ppt protocol power point presentation
tcpip.ppt
tcpip.ppt

Recently uploaded (20)

PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
PDF
Complications of Minimal Access-Surgery.pdf
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
Empowerment Technology for Senior High School Guide
PDF
advance database management system book.pdf
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
Introduction to pro and eukaryotes and differences.pptx
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Unit 4 Computer Architecture Multicore Processor.pptx
AI-driven educational solutions for real-life interventions in the Philippine...
History, Philosophy and sociology of education (1).pptx
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
Cambridge-Practice-Tests-for-IELTS-12.docx
Paper A Mock Exam 9_ Attempt review.pdf.
Practical Manual AGRO-233 Principles and Practices of Natural Farming
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
Complications of Minimal Access-Surgery.pdf
Share_Module_2_Power_conflict_and_negotiation.pptx
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
Weekly quiz Compilation Jan -July 25.pdf
Environmental Education MCQ BD2EE - Share Source.pdf
Empowerment Technology for Senior High School Guide
advance database management system book.pdf
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Introduction to pro and eukaryotes and differences.pptx

Dumb Ways To Die: How Not To Write TCP-based Network Applications

  • 1. HOW[NOT]TO Write TCP-based Network Applications Artyom Gavrichenkov 1/x
  • 2. Based on a True Story • NOT AN AD! • Qrator: distributed network ● Custom TCP/IP at the bottom ● Custom management protocol at the top ● Interacting with plenty of Web servers and Web browsers on a daily basis ● 2 years of continuous debug^W Product ImprovementTM 2
  • 3. Issue #1 • Message delivery is unreliable in TCP.
  • 4. Issue #1 • Message delivery is unreliable in TCP: there's no estimation on when (and if) the message will arrive at all • Timeouts! • Limit all resources, including time • No action is itself an action
  • 5. Timeouts • Between recvfrom() • Between requests • Request timeout • Lifetime of a session • Lifetime of %OBJECTNAME% • Long polling may be a bad idea
  • 6. Ex. 1 • Slowloris (Apache): DoS ● (not distributed, just denial of service) • Slow HTTP POST ● Apache, IIS, Lighttpd: DoS ● Nginx: DDoS with a botnet
  • 7. Ex. 2 12 rpm AJAX page update ● Backup script switched the server off
  • 9. Content-Length – Limit resources for all actions – Custom protocol should define limits on the input length
  • 10. errno(3) – The connection may be closed for no good reason – Check errno after recvfrom(), sendto(), etc. ● ENOMEM ● ECONNRESET ● EANYTHING
  • 11. Ex. 3 ● Internet Explorer: ECONNRESET means successful connection termination – Download status is being ignored – Content-Length is being ignored
  • 12. Memory limits – Resource limits: ● Maximum – ENOMEM ● Minimum – idle wait → ECONNRESET
  • 13. Ex. 4 – DNS TTL ● Too big: days of downtime (continuous) ● Too small: days of downtime (total)
  • 14. Latency – 3-Way Handshake takes time – Do implement persistent connections! ● Do it from the very beginning
  • 15. They haven't listened to me! ● TCP – T/TCP ● HTTP/1.0 – HTTP/1.1
  • 16. Optimization – Measure! – Profile! – Emulate packet loss!
  • 17. Optimization – Text-based protocols are convenient to debug ● And you will debug – Maybe even in production – Making use of binary protocols is often a premature optimization ● BSON, Google Protocol Buffers
  • 18. Optimization ● TCP socket options: – TCP_NODELAY: disables Nagle's algorithm ● Speedup with small portions of data – TCP_CORK (Linux): multiple portions of data in a single TCP segment – "socket corking"
  • 19. Optimization ● TCP stack options: – Linux: /proc/sys/net/** ● net.ipv4.tcp_fin_timeout ● net.ipv4.tcp_{,r,w}mem ● net.core.{r,w}mem_max – Windows: HKLMSystemCurrentControlSetServicesTcpipParameters
  • 20. IPv6 ● Accidental IPv6 deployment
  • 21. • SO_REUSEADDR • sendfile(2) • select(2)/poll(2)/epoll(7) • {n,h}to{n,h}{s,l}() • int64_t vs long 21
  • 22. This is it! Artyom Gavrichenkov <ximaera@highloadlab.com>