SlideShare a Scribd company logo
1 of 35
Download to read 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

More Related Content

What's hot

BPF / XDP 8월 세미나 KossLab
BPF / XDP 8월 세미나 KossLabBPF / XDP 8월 세미나 KossLab
BPF / XDP 8월 세미나 KossLabTaeung Song
 
Ethernetの受信処理
Ethernetの受信処理Ethernetの受信処理
Ethernetの受信処理Takuya ASADA
 
Linux Performance Analysis and Tools
Linux Performance Analysis and ToolsLinux Performance Analysis and Tools
Linux Performance Analysis and ToolsBrendan Gregg
 
Kernel Recipes 2017: Using Linux perf at Netflix
Kernel Recipes 2017: Using Linux perf at NetflixKernel Recipes 2017: Using Linux perf at Netflix
Kernel Recipes 2017: Using Linux perf at NetflixBrendan Gregg
 
(CMP402) Amazon EC2 Instances Deep Dive
(CMP402) Amazon EC2 Instances Deep Dive(CMP402) Amazon EC2 Instances Deep Dive
(CMP402) Amazon EC2 Instances Deep DiveAmazon Web Services
 
OVS and DPDK - T.F. Herbert, K. Traynor, M. Gray
OVS and DPDK - T.F. Herbert, K. Traynor, M. GrayOVS and DPDK - T.F. Herbert, K. Traynor, M. Gray
OVS and DPDK - T.F. Herbert, K. Traynor, M. Grayharryvanhaaren
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at NetflixBrendan Gregg
 
Producer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache KafkaProducer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache KafkaJiangjie Qin
 
Linux Systems Performance 2016
Linux Systems Performance 2016Linux Systems Performance 2016
Linux Systems Performance 2016Brendan Gregg
 
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...OpenStack Korea Community
 
OSC2011 Tokyo/Fall 濃いバナ(virtio)
OSC2011 Tokyo/Fall 濃いバナ(virtio)OSC2011 Tokyo/Fall 濃いバナ(virtio)
OSC2011 Tokyo/Fall 濃いバナ(virtio)Takeshi HASEGAWA
 
DPDK: Multi Architecture High Performance Packet Processing
DPDK: Multi Architecture High Performance Packet ProcessingDPDK: Multi Architecture High Performance Packet Processing
DPDK: Multi Architecture High Performance Packet ProcessingMichelle Holley
 
[OpenStack Days Korea 2016] Track1 - All flash CEPH 구성 및 최적화
[OpenStack Days Korea 2016] Track1 - All flash CEPH 구성 및 최적화[OpenStack Days Korea 2016] Track1 - All flash CEPH 구성 및 최적화
[OpenStack Days Korea 2016] Track1 - All flash CEPH 구성 및 최적화OpenStack Korea Community
 
Webinar: 99 Ways to Enrich Streaming Data with Apache Flink - Konstantin Knauf
Webinar: 99 Ways to Enrich Streaming Data with Apache Flink - Konstantin KnaufWebinar: 99 Ways to Enrich Streaming Data with Apache Flink - Konstantin Knauf
Webinar: 99 Ways to Enrich Streaming Data with Apache Flink - Konstantin KnaufVerverica
 
Cfgmgmtcamp 2023 — eBPF Superpowers
Cfgmgmtcamp 2023 — eBPF SuperpowersCfgmgmtcamp 2023 — eBPF Superpowers
Cfgmgmtcamp 2023 — eBPF SuperpowersRaphaël PINSON
 
eBPF - Rethinking the Linux Kernel
eBPF - Rethinking the Linux KerneleBPF - Rethinking the Linux Kernel
eBPF - Rethinking the Linux KernelThomas Graf
 

What's hot (20)

BPF / XDP 8월 세미나 KossLab
BPF / XDP 8월 세미나 KossLabBPF / XDP 8월 세미나 KossLab
BPF / XDP 8월 세미나 KossLab
 
Ethernetの受信処理
Ethernetの受信処理Ethernetの受信処理
Ethernetの受信処理
 
Linux Performance Analysis and Tools
Linux Performance Analysis and ToolsLinux Performance Analysis and Tools
Linux Performance Analysis and Tools
 
Kernel Recipes 2017: Using Linux perf at Netflix
Kernel Recipes 2017: Using Linux perf at NetflixKernel Recipes 2017: Using Linux perf at Netflix
Kernel Recipes 2017: Using Linux perf at Netflix
 
(CMP402) Amazon EC2 Instances Deep Dive
(CMP402) Amazon EC2 Instances Deep Dive(CMP402) Amazon EC2 Instances Deep Dive
(CMP402) Amazon EC2 Instances Deep Dive
 
The basics of fluentd
The basics of fluentdThe basics of fluentd
The basics of fluentd
 
OVS and DPDK - T.F. Herbert, K. Traynor, M. Gray
OVS and DPDK - T.F. Herbert, K. Traynor, M. GrayOVS and DPDK - T.F. Herbert, K. Traynor, M. Gray
OVS and DPDK - T.F. Herbert, K. Traynor, M. Gray
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at Netflix
 
Producer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache KafkaProducer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache Kafka
 
Linux Systems Performance 2016
Linux Systems Performance 2016Linux Systems Performance 2016
Linux Systems Performance 2016
 
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
 
DPDK QoS
DPDK QoSDPDK QoS
DPDK QoS
 
Redis
RedisRedis
Redis
 
OSC2011 Tokyo/Fall 濃いバナ(virtio)
OSC2011 Tokyo/Fall 濃いバナ(virtio)OSC2011 Tokyo/Fall 濃いバナ(virtio)
OSC2011 Tokyo/Fall 濃いバナ(virtio)
 
DPDK: Multi Architecture High Performance Packet Processing
DPDK: Multi Architecture High Performance Packet ProcessingDPDK: Multi Architecture High Performance Packet Processing
DPDK: Multi Architecture High Performance Packet Processing
 
[OpenStack Days Korea 2016] Track1 - All flash CEPH 구성 및 최적화
[OpenStack Days Korea 2016] Track1 - All flash CEPH 구성 및 최적화[OpenStack Days Korea 2016] Track1 - All flash CEPH 구성 및 최적화
[OpenStack Days Korea 2016] Track1 - All flash CEPH 구성 및 최적화
 
Webinar: 99 Ways to Enrich Streaming Data with Apache Flink - Konstantin Knauf
Webinar: 99 Ways to Enrich Streaming Data with Apache Flink - Konstantin KnaufWebinar: 99 Ways to Enrich Streaming Data with Apache Flink - Konstantin Knauf
Webinar: 99 Ways to Enrich Streaming Data with Apache Flink - Konstantin Knauf
 
美团技术团队 - KVM性能优化
美团技术团队 - KVM性能优化美团技术团队 - KVM性能优化
美团技术团队 - KVM性能优化
 
Cfgmgmtcamp 2023 — eBPF Superpowers
Cfgmgmtcamp 2023 — eBPF SuperpowersCfgmgmtcamp 2023 — eBPF Superpowers
Cfgmgmtcamp 2023 — eBPF Superpowers
 
eBPF - Rethinking the Linux Kernel
eBPF - Rethinking the Linux KerneleBPF - Rethinking the Linux Kernel
eBPF - Rethinking the Linux Kernel
 

Similar to 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
 

Similar to 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
 

More from Joshua Zhu

阿里开源经验分享
阿里开源经验分享阿里开源经验分享
阿里开源经验分享Joshua Zhu
 
阿里云CDN技术演进之路
阿里云CDN技术演进之路阿里云CDN技术演进之路
阿里云CDN技术演进之路Joshua Zhu
 
阿里CDN技术揭秘
阿里CDN技术揭秘阿里CDN技术揭秘
阿里CDN技术揭秘Joshua Zhu
 
Nginx深度開發與客制化
Nginx深度開發與客制化Nginx深度開發與客制化
Nginx深度開發與客制化Joshua Zhu
 
Hacking Nginx at Taobao
Hacking Nginx at TaobaoHacking Nginx at Taobao
Hacking Nginx at TaobaoJoshua Zhu
 
Velocity 2010 Highlights
Velocity 2010 HighlightsVelocity 2010 Highlights
Velocity 2010 HighlightsJoshua Zhu
 

More from Joshua Zhu (6)

阿里开源经验分享
阿里开源经验分享阿里开源经验分享
阿里开源经验分享
 
阿里云CDN技术演进之路
阿里云CDN技术演进之路阿里云CDN技术演进之路
阿里云CDN技术演进之路
 
阿里CDN技术揭秘
阿里CDN技术揭秘阿里CDN技术揭秘
阿里CDN技术揭秘
 
Nginx深度開發與客制化
Nginx深度開發與客制化Nginx深度開發與客制化
Nginx深度開發與客制化
 
Hacking Nginx at Taobao
Hacking Nginx at TaobaoHacking Nginx at Taobao
Hacking Nginx at Taobao
 
Velocity 2010 Highlights
Velocity 2010 HighlightsVelocity 2010 Highlights
Velocity 2010 Highlights
 

Recently uploaded

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

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