SlideShare uma empresa Scribd logo
1 de 35
Baixar para ler offline
Tips on High Performance
   Server Programming
        Joshua Zhu
       June 9, 2009
Agenda
•   Fundamentals
•   Best practices and common tricks
•   Design issues
•   Tools and resources
Key Rules
• Do NOT block
• Avoid excessive system calls
• Cache/preprocess as much as possible
• Use efficient algorithms and data structures
• Threads are usually a bad idea
• Separate the I/O code from the business-logic
  code
• Keep the most heavily used data near the CPU
• Tune against the bottleneck
I/O Models
•   Blocking
•   Non-blocking
•   I/O multiplexing
•   Signal-driven I/O
•   Asynchronous I/O
I/O Multiplexing
•   Select
•   Poll
•   /dev/poll
•   Epoll/kqueue
    – Level triggered
    – Edge triggered
I/O Strategies
•   1 thread, non-blocking, level-triggered
•   1 thread, non-blocking, edge-triggered
•   1 thread, AIO
•   1 thread per client
•   Build the server code into the kernel
Let’s Face the C10K Problem
• 10000 connections
  – CPU/memory usage per connection
• 10000 hits/sec
  – 10 us per hit
     • Instruction (ns)
     • System call (us)
Agenda
•   Fundamentals
•   Best practices and common tricks
•   Design issues
•   Tools and resources
The Event-driven Model
while (true) {
     for t in run_tasks:
               t.handler();

     update_time(&now);
     timeout = ETERNITY;

     for t in wait_tasks: /* sorted already */
              if (t.time <= now) {
                             t.timeout_handler();
              } else {
                             timeout = t.time - now;
                             break;
              }

     nevents = poll_function(events, timeout);
     for i in nevents:
               task t;

              if (events[i].type == READ) {
                             t.handler = read_handler;
              } else (events[i].type == WRITE) {
                             t.handler = write_handler;
              }

              run_tasks_add(t);
}
Scheduler
• Task scheduling
  – Run queue
  – Wait queue
• Timers
  – Time jumps
  – The next timeout
     • Pass to select()/poll()/epoll_wait()...
  – Data structures
     • Red-black tree
     • Min-heap
     • Timer wheel
Unify Multiple Event Sources
• I/O events
• Timer events
• Signals/threads
  – Use a pipe or socketpair
    • Register the read end in the event loop
    • Notify the event loop by writing to the write end
Buffer Management
• Fixed size or not
• R/W pointers operation
  – Producer/consumer
• Circular buffer
• Single buffering
• Buffer chain
Memory
• Memory fragment
   – Memory pool
      • Fixed size
          – MRU
      • Non-fixed size
   – Slab allocator
• Memory operations are expensive
   – Allocation/free
   – Data copies
• Pre-allocation/static-allocation
   – Array
Strings
• Gotchas
  – Strlen()
     • Sizeof() - 1
  – Strncpy()
     • Strlcpy()
  – Vsnprintf()
  –…
• Algorithms
  – KMP/BM
  – AC/WM
  –…
Caching
• Time
  – Reduce the number of gettimeofday() calls
  – Time resolution
     • ms or sec?
• Content
  – Files
     • In-memory buffering
  – Database
     • Memcached
• Preprocessing
Accept() Strategies
• Accept-limit
  – Multi-accept
  – Accept-mutex
• The thundering herd problem
  – Polling functions
  – Kernels
  – The amount of processes/threads
Concurrency
• Threads
  – Pros
     • Utilize all the CPUs
     • True CPU concurrency
  – Cons
     • Context switches
     • Locks hurt performance
           – Deadlocks
           – Starvation
           – Race conditions
     • Error prone and hard to debug
     • Hard limits of operating systems
Concurrency (cont’d)
• Categorize your service
  – CPU-bound
  – I/O-bound
• Models
  – Thread pool
  – Process pool
  – SEDA
  – Master/workers
• CPU affinity
Advanced I/O Functions
• Gather read, scatter write
  – Readv/writev
• Sendfile
• Mmap
• Splice and tee
Take Advantage of TCP/IP Options
• TCP/IP options
  – SO_REUSEADDR
  – SO_RCVBUF/SO_SNDBUF
  – TCP_CORK
  – TCP_NODELAY
  – TCP_DEFER_ACCEPT
  –…
Misc.
• Byte order
  – Little-endian
  – Big-endian
• Max open file number
  – Ulimit/setrlimit
Agenda
•   Fundamentals
•   Best practices and common tricks
•   Design issues
•   Tools and resources
Protocol
• Readability
  – Binary
  – Textual
• Compatibility
• Security
  – Heart beat
  – Invalid data
• The state machine (FSM)
  – Granularity
  – Traceability
Security
•   Timeouts
•   Bad data
•   Buffer overflow
•   DOS attack
•   Encryption
•   Privilege
•   Working directory
Flexibility
• Modularize
  – Modules
  – Plugins
• Scriptable
  – Lua
• Hot code update
• HA
Introspection
• Statistics
  – SNMP
• Debugable
• Tunable
• Logs
Patterns
•   Reactor
•   Proactor
•   Half-Sync/Half-Async
•   Leader/Followers
•   …
Choose a Suitable Language
•   C
•   C++
•   Java
•   Erlang
•   …
The Devil Hides in the Details
• Find out the shortest plank in the bucket
   – Profile/benchmark
• Take care of every line of your code!
   – Return values
   – Error code
      • EINTR
      • SIGPIPE
      • …
• Tune your operating system if necessary
   – /proc
• Make sure hardware is not the bottleneck
   – Network cards
   – Disk
   – …
Agenda
•   Fundamentals
•   Best practices and common tricks
•   Design issues
•   Tools and resources
Sharpen Your Tools
•   Ping
•   Traceroute
•   Netstat
•   Lsof
•   Strace
•   Nc
•   Wireshark
•   Gprof
•   Valgrind
•   Vmstat/iostat/dstat
•   Dot/gnuplot
Understand TCP/IP Well
• Three-way handshake
• Connection tear-down
• TCP state transition
  – TIME_WAIT
  – CLOSE_WAIT
  –…
Learn By Reading Code
• Frameworks
  –   ACE
  –   Libevent/libev
  –   Boost::asio
  –   …
• Servers
  –   HAProxy
  –   Nginx
  –   Lighttpd
  –   Memcached
  –   MySQL Proxy
  –   …
Recommended Books
• Advanced Programming in the UNIX
  Environment
• UNIX Network Programming
• TCP/IP Illustrated
• Effective TCP/IP Programming
• Pattern-Oriented Software Architecture
• C++ Network Programming
• Programming With POSIX Threads
• Introduction to Algorithms
Thank You!
Visit www.zhuzhaoyuan.com for more info

Mais conteúdo relacionado

Mais procurados

The Patterns of Distributed Logging and Containers
The Patterns of Distributed Logging and ContainersThe Patterns of Distributed Logging and Containers
The Patterns of Distributed Logging and ContainersSATOSHI TAGOMORI
 
Linux Systems Performance 2016
Linux Systems Performance 2016Linux Systems Performance 2016
Linux Systems Performance 2016Brendan Gregg
 
Performance Analysis: The USE Method
Performance Analysis: The USE MethodPerformance Analysis: The USE Method
Performance Analysis: The USE MethodBrendan Gregg
 
The Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast StorageThe Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast StorageKernel TLV
 
eBPF Perf Tools 2019
eBPF Perf Tools 2019eBPF Perf Tools 2019
eBPF Perf Tools 2019Brendan Gregg
 
High Availability Content Caching with NGINX
High Availability Content Caching with NGINXHigh Availability Content Caching with NGINX
High Availability Content Caching with NGINXNGINX, Inc.
 
[오픈소스컨설팅] 아파치톰캣 운영가이드 v1.3
[오픈소스컨설팅] 아파치톰캣 운영가이드 v1.3[오픈소스컨설팅] 아파치톰캣 운영가이드 v1.3
[오픈소스컨설팅] 아파치톰캣 운영가이드 v1.3Ji-Woong Choi
 
Scylla Summit 2022: How to Migrate a Counter Table for 68 Billion Records
Scylla Summit 2022: How to Migrate a Counter Table for 68 Billion RecordsScylla Summit 2022: How to Migrate a Counter Table for 68 Billion Records
Scylla Summit 2022: How to Migrate a Counter Table for 68 Billion RecordsScyllaDB
 
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...Flink Forward
 
Accelerating Virtual Machine Access with the Storage Performance Development ...
Accelerating Virtual Machine Access with the Storage Performance Development ...Accelerating Virtual Machine Access with the Storage Performance Development ...
Accelerating Virtual Machine Access with the Storage Performance Development ...Michelle Holley
 
Intel DPDK Step by Step instructions
Intel DPDK Step by Step instructionsIntel DPDK Step by Step instructions
Intel DPDK Step by Step instructionsHisaki Ohara
 
DPDK & Layer 4 Packet Processing
DPDK & Layer 4 Packet ProcessingDPDK & Layer 4 Packet Processing
DPDK & Layer 4 Packet ProcessingMichelle Holley
 
NGINX: Basics and Best Practices
NGINX: Basics and Best PracticesNGINX: Basics and Best Practices
NGINX: Basics and Best PracticesNGINX, Inc.
 
BPF - in-kernel virtual machine
BPF - in-kernel virtual machineBPF - in-kernel virtual machine
BPF - in-kernel virtual machineAlexei Starovoitov
 
Revisit DCA, PCIe TPH and DDIO
Revisit DCA, PCIe TPH and DDIORevisit DCA, PCIe TPH and DDIO
Revisit DCA, PCIe TPH and DDIOHisaki Ohara
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisDvir Volk
 
Monitoring IO performance with iostat and pt-diskstats
Monitoring IO performance with iostat and pt-diskstatsMonitoring IO performance with iostat and pt-diskstats
Monitoring IO performance with iostat and pt-diskstatsBen Mildren
 

Mais procurados (20)

The Patterns of Distributed Logging and Containers
The Patterns of Distributed Logging and ContainersThe Patterns of Distributed Logging and Containers
The Patterns of Distributed Logging and Containers
 
Linux Systems Performance 2016
Linux Systems Performance 2016Linux Systems Performance 2016
Linux Systems Performance 2016
 
Performance Analysis: The USE Method
Performance Analysis: The USE MethodPerformance Analysis: The USE Method
Performance Analysis: The USE Method
 
The Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast StorageThe Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast Storage
 
Dpdk performance
Dpdk performanceDpdk performance
Dpdk performance
 
Intel dpdk Tutorial
Intel dpdk TutorialIntel dpdk Tutorial
Intel dpdk Tutorial
 
eBPF Perf Tools 2019
eBPF Perf Tools 2019eBPF Perf Tools 2019
eBPF Perf Tools 2019
 
High Availability Content Caching with NGINX
High Availability Content Caching with NGINXHigh Availability Content Caching with NGINX
High Availability Content Caching with NGINX
 
[오픈소스컨설팅] 아파치톰캣 운영가이드 v1.3
[오픈소스컨설팅] 아파치톰캣 운영가이드 v1.3[오픈소스컨설팅] 아파치톰캣 운영가이드 v1.3
[오픈소스컨설팅] 아파치톰캣 운영가이드 v1.3
 
Scylla Summit 2022: How to Migrate a Counter Table for 68 Billion Records
Scylla Summit 2022: How to Migrate a Counter Table for 68 Billion RecordsScylla Summit 2022: How to Migrate a Counter Table for 68 Billion Records
Scylla Summit 2022: How to Migrate a Counter Table for 68 Billion Records
 
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
 
Accelerating Virtual Machine Access with the Storage Performance Development ...
Accelerating Virtual Machine Access with the Storage Performance Development ...Accelerating Virtual Machine Access with the Storage Performance Development ...
Accelerating Virtual Machine Access with the Storage Performance Development ...
 
Intel DPDK Step by Step instructions
Intel DPDK Step by Step instructionsIntel DPDK Step by Step instructions
Intel DPDK Step by Step instructions
 
DPDK & Layer 4 Packet Processing
DPDK & Layer 4 Packet ProcessingDPDK & Layer 4 Packet Processing
DPDK & Layer 4 Packet Processing
 
NGINX: Basics and Best Practices
NGINX: Basics and Best PracticesNGINX: Basics and Best Practices
NGINX: Basics and Best Practices
 
BPF - in-kernel virtual machine
BPF - in-kernel virtual machineBPF - in-kernel virtual machine
BPF - in-kernel virtual machine
 
Revisit DCA, PCIe TPH and DDIO
Revisit DCA, PCIe TPH and DDIORevisit DCA, PCIe TPH and DDIO
Revisit DCA, PCIe TPH and DDIO
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
Dpdk applications
Dpdk applicationsDpdk applications
Dpdk applications
 
Monitoring IO performance with iostat and pt-diskstats
Monitoring IO performance with iostat and pt-diskstatsMonitoring IO performance with iostat and pt-diskstats
Monitoring IO performance with iostat and pt-diskstats
 

Destaque

阿里CDN技术揭秘
阿里CDN技术揭秘阿里CDN技术揭秘
阿里CDN技术揭秘Joshua Zhu
 
阿里云CDN技术演进之路
阿里云CDN技术演进之路阿里云CDN技术演进之路
阿里云CDN技术演进之路Joshua Zhu
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx InternalsJoshua Zhu
 
阿里开源经验分享
阿里开源经验分享阿里开源经验分享
阿里开源经验分享Joshua Zhu
 
Velocity 2010 Highlights
Velocity 2010 HighlightsVelocity 2010 Highlights
Velocity 2010 HighlightsJoshua Zhu
 
NGINX High-performance Caching
NGINX High-performance CachingNGINX High-performance Caching
NGINX High-performance CachingNGINX, Inc.
 

Destaque (6)

阿里CDN技术揭秘
阿里CDN技术揭秘阿里CDN技术揭秘
阿里CDN技术揭秘
 
阿里云CDN技术演进之路
阿里云CDN技术演进之路阿里云CDN技术演进之路
阿里云CDN技术演进之路
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
 
阿里开源经验分享
阿里开源经验分享阿里开源经验分享
阿里开源经验分享
 
Velocity 2010 Highlights
Velocity 2010 HighlightsVelocity 2010 Highlights
Velocity 2010 Highlights
 
NGINX High-performance Caching
NGINX High-performance CachingNGINX High-performance Caching
NGINX High-performance Caching
 

Semelhante a Tips on High Performance Server Programming

Perfmon And Profiler 101
Perfmon And Profiler 101Perfmon And Profiler 101
Perfmon And Profiler 101Quest Software
 
Evergreen Sysadmin Survival Skills
Evergreen Sysadmin Survival SkillsEvergreen Sysadmin Survival Skills
Evergreen Sysadmin Survival SkillsEvergreen ILS
 
Capacity Planning for fun & profit
Capacity Planning for fun & profitCapacity Planning for fun & profit
Capacity Planning for fun & profitRodrigo Campos
 
Optimizing Python
Optimizing PythonOptimizing Python
Optimizing PythonAdimianBE
 
Web 2.0 Performance and Reliability: How to Run Large Web Apps
Web 2.0 Performance and Reliability: How to Run Large Web AppsWeb 2.0 Performance and Reliability: How to Run Large Web Apps
Web 2.0 Performance and Reliability: How to Run Large Web Appsadunne
 
Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorialoscon2007
 
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...Red Hat Developers
 
Benchmarks, performance, scalability, and capacity what's behind the numbers
Benchmarks, performance, scalability, and capacity what's behind the numbersBenchmarks, performance, scalability, and capacity what's behind the numbers
Benchmarks, performance, scalability, and capacity what's behind the numbersJustin Dorfman
 
Benchmarks, performance, scalability, and capacity what s behind the numbers...
Benchmarks, performance, scalability, and capacity  what s behind the numbers...Benchmarks, performance, scalability, and capacity  what s behind the numbers...
Benchmarks, performance, scalability, and capacity what s behind the numbers...james tong
 
Understanding and Designing Ultra low latency systems | Low Latency | Ultra L...
Understanding and Designing Ultra low latency systems | Low Latency | Ultra L...Understanding and Designing Ultra low latency systems | Low Latency | Ultra L...
Understanding and Designing Ultra low latency systems | Low Latency | Ultra L...Anand Narayanan
 
Kernel Recipes 2016 - Speeding up development by setting up a kernel build farm
Kernel Recipes 2016 - Speeding up development by setting up a kernel build farmKernel Recipes 2016 - Speeding up development by setting up a kernel build farm
Kernel Recipes 2016 - Speeding up development by setting up a kernel build farmAnne Nicolas
 
Using the big guns: Advanced OS performance tools for troubleshooting databas...
Using the big guns: Advanced OS performance tools for troubleshooting databas...Using the big guns: Advanced OS performance tools for troubleshooting databas...
Using the big guns: Advanced OS performance tools for troubleshooting databas...Nikolay Savvinov
 
Lightweight Grids With Terracotta
Lightweight Grids With TerracottaLightweight Grids With Terracotta
Lightweight Grids With TerracottaPT.JUG
 
New School Man-in-the-Middle
New School Man-in-the-MiddleNew School Man-in-the-Middle
New School Man-in-the-MiddleTom Eston
 
Ceph Day Melbourne - Troubleshooting Ceph
Ceph Day Melbourne - Troubleshooting Ceph Ceph Day Melbourne - Troubleshooting Ceph
Ceph Day Melbourne - Troubleshooting Ceph Ceph Community
 
Linux Performance Tools 2014
Linux Performance Tools 2014Linux Performance Tools 2014
Linux Performance Tools 2014Brendan Gregg
 

Semelhante a Tips on High Performance Server Programming (20)

Server Tips
Server TipsServer Tips
Server Tips
 
Perfmon And Profiler 101
Perfmon And Profiler 101Perfmon And Profiler 101
Perfmon And Profiler 101
 
Evergreen Sysadmin Survival Skills
Evergreen Sysadmin Survival SkillsEvergreen Sysadmin Survival Skills
Evergreen Sysadmin Survival Skills
 
MySQL Tuning
MySQL TuningMySQL Tuning
MySQL Tuning
 
Capacity Planning for fun & profit
Capacity Planning for fun & profitCapacity Planning for fun & profit
Capacity Planning for fun & profit
 
Optimizing Python
Optimizing PythonOptimizing Python
Optimizing Python
 
Web 2.0 Performance and Reliability: How to Run Large Web Apps
Web 2.0 Performance and Reliability: How to Run Large Web AppsWeb 2.0 Performance and Reliability: How to Run Large Web Apps
Web 2.0 Performance and Reliability: How to Run Large Web Apps
 
Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorial
 
Performance Whackamole (short version)
Performance Whackamole (short version)Performance Whackamole (short version)
Performance Whackamole (short version)
 
Performance
PerformancePerformance
Performance
 
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...
 
Benchmarks, performance, scalability, and capacity what's behind the numbers
Benchmarks, performance, scalability, and capacity what's behind the numbersBenchmarks, performance, scalability, and capacity what's behind the numbers
Benchmarks, performance, scalability, and capacity what's behind the numbers
 
Benchmarks, performance, scalability, and capacity what s behind the numbers...
Benchmarks, performance, scalability, and capacity  what s behind the numbers...Benchmarks, performance, scalability, and capacity  what s behind the numbers...
Benchmarks, performance, scalability, and capacity what s behind the numbers...
 
Understanding and Designing Ultra low latency systems | Low Latency | Ultra L...
Understanding and Designing Ultra low latency systems | Low Latency | Ultra L...Understanding and Designing Ultra low latency systems | Low Latency | Ultra L...
Understanding and Designing Ultra low latency systems | Low Latency | Ultra L...
 
Kernel Recipes 2016 - Speeding up development by setting up a kernel build farm
Kernel Recipes 2016 - Speeding up development by setting up a kernel build farmKernel Recipes 2016 - Speeding up development by setting up a kernel build farm
Kernel Recipes 2016 - Speeding up development by setting up a kernel build farm
 
Using the big guns: Advanced OS performance tools for troubleshooting databas...
Using the big guns: Advanced OS performance tools for troubleshooting databas...Using the big guns: Advanced OS performance tools for troubleshooting databas...
Using the big guns: Advanced OS performance tools for troubleshooting databas...
 
Lightweight Grids With Terracotta
Lightweight Grids With TerracottaLightweight Grids With Terracotta
Lightweight Grids With Terracotta
 
New School Man-in-the-Middle
New School Man-in-the-MiddleNew School Man-in-the-Middle
New School Man-in-the-Middle
 
Ceph Day Melbourne - Troubleshooting Ceph
Ceph Day Melbourne - Troubleshooting Ceph Ceph Day Melbourne - Troubleshooting Ceph
Ceph Day Melbourne - Troubleshooting Ceph
 
Linux Performance Tools 2014
Linux Performance Tools 2014Linux Performance Tools 2014
Linux Performance Tools 2014
 

Último

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Último (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Tips on High Performance Server Programming

  • 1. Tips on High Performance Server Programming Joshua Zhu June 9, 2009
  • 2. Agenda • Fundamentals • Best practices and common tricks • Design issues • Tools and resources
  • 3. Key Rules • Do NOT block • Avoid excessive system calls • Cache/preprocess as much as possible • Use efficient algorithms and data structures • Threads are usually a bad idea • Separate the I/O code from the business-logic code • Keep the most heavily used data near the CPU • Tune against the bottleneck
  • 4. I/O Models • Blocking • Non-blocking • I/O multiplexing • Signal-driven I/O • Asynchronous I/O
  • 5. I/O Multiplexing • Select • Poll • /dev/poll • Epoll/kqueue – Level triggered – Edge triggered
  • 6. I/O Strategies • 1 thread, non-blocking, level-triggered • 1 thread, non-blocking, edge-triggered • 1 thread, AIO • 1 thread per client • Build the server code into the kernel
  • 7. Let’s Face the C10K Problem • 10000 connections – CPU/memory usage per connection • 10000 hits/sec – 10 us per hit • Instruction (ns) • System call (us)
  • 8. Agenda • Fundamentals • Best practices and common tricks • Design issues • Tools and resources
  • 9. The Event-driven Model while (true) { for t in run_tasks: t.handler(); update_time(&now); timeout = ETERNITY; for t in wait_tasks: /* sorted already */ if (t.time <= now) { t.timeout_handler(); } else { timeout = t.time - now; break; } nevents = poll_function(events, timeout); for i in nevents: task t; if (events[i].type == READ) { t.handler = read_handler; } else (events[i].type == WRITE) { t.handler = write_handler; } run_tasks_add(t); }
  • 10. Scheduler • Task scheduling – Run queue – Wait queue • Timers – Time jumps – The next timeout • Pass to select()/poll()/epoll_wait()... – Data structures • Red-black tree • Min-heap • Timer wheel
  • 11. Unify Multiple Event Sources • I/O events • Timer events • Signals/threads – Use a pipe or socketpair • Register the read end in the event loop • Notify the event loop by writing to the write end
  • 12. Buffer Management • Fixed size or not • R/W pointers operation – Producer/consumer • Circular buffer • Single buffering • Buffer chain
  • 13. Memory • Memory fragment – Memory pool • Fixed size – MRU • Non-fixed size – Slab allocator • Memory operations are expensive – Allocation/free – Data copies • Pre-allocation/static-allocation – Array
  • 14. Strings • Gotchas – Strlen() • Sizeof() - 1 – Strncpy() • Strlcpy() – Vsnprintf() –… • Algorithms – KMP/BM – AC/WM –…
  • 15. Caching • Time – Reduce the number of gettimeofday() calls – Time resolution • ms or sec? • Content – Files • In-memory buffering – Database • Memcached • Preprocessing
  • 16. Accept() Strategies • Accept-limit – Multi-accept – Accept-mutex • The thundering herd problem – Polling functions – Kernels – The amount of processes/threads
  • 17. Concurrency • Threads – Pros • Utilize all the CPUs • True CPU concurrency – Cons • Context switches • Locks hurt performance – Deadlocks – Starvation – Race conditions • Error prone and hard to debug • Hard limits of operating systems
  • 18. Concurrency (cont’d) • Categorize your service – CPU-bound – I/O-bound • Models – Thread pool – Process pool – SEDA – Master/workers • CPU affinity
  • 19. Advanced I/O Functions • Gather read, scatter write – Readv/writev • Sendfile • Mmap • Splice and tee
  • 20. Take Advantage of TCP/IP Options • TCP/IP options – SO_REUSEADDR – SO_RCVBUF/SO_SNDBUF – TCP_CORK – TCP_NODELAY – TCP_DEFER_ACCEPT –…
  • 21. Misc. • Byte order – Little-endian – Big-endian • Max open file number – Ulimit/setrlimit
  • 22. Agenda • Fundamentals • Best practices and common tricks • Design issues • Tools and resources
  • 23. Protocol • Readability – Binary – Textual • Compatibility • Security – Heart beat – Invalid data • The state machine (FSM) – Granularity – Traceability
  • 24. Security • Timeouts • Bad data • Buffer overflow • DOS attack • Encryption • Privilege • Working directory
  • 25. Flexibility • Modularize – Modules – Plugins • Scriptable – Lua • Hot code update • HA
  • 26. Introspection • Statistics – SNMP • Debugable • Tunable • Logs
  • 27. Patterns • Reactor • Proactor • Half-Sync/Half-Async • Leader/Followers • …
  • 28. Choose a Suitable Language • C • C++ • Java • Erlang • …
  • 29. The Devil Hides in the Details • Find out the shortest plank in the bucket – Profile/benchmark • Take care of every line of your code! – Return values – Error code • EINTR • SIGPIPE • … • Tune your operating system if necessary – /proc • Make sure hardware is not the bottleneck – Network cards – Disk – …
  • 30. Agenda • Fundamentals • Best practices and common tricks • Design issues • Tools and resources
  • 31. Sharpen Your Tools • Ping • Traceroute • Netstat • Lsof • Strace • Nc • Wireshark • Gprof • Valgrind • Vmstat/iostat/dstat • Dot/gnuplot
  • 32. Understand TCP/IP Well • Three-way handshake • Connection tear-down • TCP state transition – TIME_WAIT – CLOSE_WAIT –…
  • 33. Learn By Reading Code • Frameworks – ACE – Libevent/libev – Boost::asio – … • Servers – HAProxy – Nginx – Lighttpd – Memcached – MySQL Proxy – …
  • 34. Recommended Books • Advanced Programming in the UNIX Environment • UNIX Network Programming • TCP/IP Illustrated • Effective TCP/IP Programming • Pattern-Oriented Software Architecture • C++ Network Programming • Programming With POSIX Threads • Introduction to Algorithms