SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Extending Flink SQL for stream processing use cases
Extending Flink SQL for stream processing use casesExtending Flink SQL for stream processing use cases
Extending Flink SQL for stream processing use casesFlink Forward
 
Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...
Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...
Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...Flink Forward
 
Apache Flink in the Cloud-Native Era
Apache Flink in the Cloud-Native EraApache Flink in the Cloud-Native Era
Apache Flink in the Cloud-Native EraFlink Forward
 
Deploy Secure and Scalable Services Across Kubernetes Clusters with NATS
Deploy Secure and Scalable Services Across Kubernetes Clusters with NATSDeploy Secure and Scalable Services Across Kubernetes Clusters with NATS
Deploy Secure and Scalable Services Across Kubernetes Clusters with NATSNATS
 
Brooklin Mirror Maker - How and why we moved away from Kafka Mirror Maker
Brooklin Mirror Maker - How and why we moved away from Kafka Mirror MakerBrooklin Mirror Maker - How and why we moved away from Kafka Mirror Maker
Brooklin Mirror Maker - How and why we moved away from Kafka Mirror MakerShun-ping Chiu
 
Stream Processing 과 Confluent Cloud 시작하기
Stream Processing 과 Confluent Cloud 시작하기Stream Processing 과 Confluent Cloud 시작하기
Stream Processing 과 Confluent Cloud 시작하기confluent
 
Maxim Fateev - Beyond the Watermark- On-Demand Backfilling in Flink
Maxim Fateev - Beyond the Watermark- On-Demand Backfilling in FlinkMaxim Fateev - Beyond the Watermark- On-Demand Backfilling in Flink
Maxim Fateev - Beyond the Watermark- On-Demand Backfilling in FlinkFlink Forward
 
The top 3 challenges running multi-tenant Flink at scale
The top 3 challenges running multi-tenant Flink at scaleThe top 3 challenges running multi-tenant Flink at scale
The top 3 challenges running multi-tenant Flink at scaleFlink Forward
 
MongoDB vs. Postgres Benchmarks
MongoDB vs. Postgres Benchmarks MongoDB vs. Postgres Benchmarks
MongoDB vs. Postgres Benchmarks EDB
 
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안SANG WON PARK
 
Exactly-Once Financial Data Processing at Scale with Flink and Pinot
Exactly-Once Financial Data Processing at Scale with Flink and PinotExactly-Once Financial Data Processing at Scale with Flink and Pinot
Exactly-Once Financial Data Processing at Scale with Flink and PinotFlink Forward
 
Pinot: Realtime OLAP for 530 Million Users - Sigmod 2018
Pinot: Realtime OLAP for 530 Million Users - Sigmod 2018Pinot: Realtime OLAP for 530 Million Users - Sigmod 2018
Pinot: Realtime OLAP for 530 Million Users - Sigmod 2018Seunghyun Lee
 
Grafana Loki: like Prometheus, but for Logs
Grafana Loki: like Prometheus, but for LogsGrafana Loki: like Prometheus, but for Logs
Grafana Loki: like Prometheus, but for LogsMarco Pracucci
 
The Flux Capacitor of Kafka Streams and ksqlDB (Matthias J. Sax, Confluent) K...
The Flux Capacitor of Kafka Streams and ksqlDB (Matthias J. Sax, Confluent) K...The Flux Capacitor of Kafka Streams and ksqlDB (Matthias J. Sax, Confluent) K...
The Flux Capacitor of Kafka Streams and ksqlDB (Matthias J. Sax, Confluent) K...HostedbyConfluent
 
Spark Operator—Deploy, Manage and Monitor Spark clusters on Kubernetes
 Spark Operator—Deploy, Manage and Monitor Spark clusters on Kubernetes Spark Operator—Deploy, Manage and Monitor Spark clusters on Kubernetes
Spark Operator—Deploy, Manage and Monitor Spark clusters on KubernetesDatabricks
 
Optimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performanceOptimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performanceMariaDB plc
 
Building a fully managed stream processing platform on Flink at scale for Lin...
Building a fully managed stream processing platform on Flink at scale for Lin...Building a fully managed stream processing platform on Flink at scale for Lin...
Building a fully managed stream processing platform on Flink at scale for Lin...Flink Forward
 
Demystifying flink memory allocation and tuning - Roshan Naik, Uber
Demystifying flink memory allocation and tuning - Roshan Naik, UberDemystifying flink memory allocation and tuning - Roshan Naik, Uber
Demystifying flink memory allocation and tuning - Roshan Naik, UberFlink Forward
 
Practical learnings from running thousands of Flink jobs
Practical learnings from running thousands of Flink jobsPractical learnings from running thousands of Flink jobs
Practical learnings from running thousands of Flink jobsFlink Forward
 
[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기NHN FORWARD
 

Was ist angesagt? (20)

Extending Flink SQL for stream processing use cases
Extending Flink SQL for stream processing use casesExtending Flink SQL for stream processing use cases
Extending Flink SQL for stream processing use cases
 
Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...
Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...
Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...
 
Apache Flink in the Cloud-Native Era
Apache Flink in the Cloud-Native EraApache Flink in the Cloud-Native Era
Apache Flink in the Cloud-Native Era
 
Deploy Secure and Scalable Services Across Kubernetes Clusters with NATS
Deploy Secure and Scalable Services Across Kubernetes Clusters with NATSDeploy Secure and Scalable Services Across Kubernetes Clusters with NATS
Deploy Secure and Scalable Services Across Kubernetes Clusters with NATS
 
Brooklin Mirror Maker - How and why we moved away from Kafka Mirror Maker
Brooklin Mirror Maker - How and why we moved away from Kafka Mirror MakerBrooklin Mirror Maker - How and why we moved away from Kafka Mirror Maker
Brooklin Mirror Maker - How and why we moved away from Kafka Mirror Maker
 
Stream Processing 과 Confluent Cloud 시작하기
Stream Processing 과 Confluent Cloud 시작하기Stream Processing 과 Confluent Cloud 시작하기
Stream Processing 과 Confluent Cloud 시작하기
 
Maxim Fateev - Beyond the Watermark- On-Demand Backfilling in Flink
Maxim Fateev - Beyond the Watermark- On-Demand Backfilling in FlinkMaxim Fateev - Beyond the Watermark- On-Demand Backfilling in Flink
Maxim Fateev - Beyond the Watermark- On-Demand Backfilling in Flink
 
The top 3 challenges running multi-tenant Flink at scale
The top 3 challenges running multi-tenant Flink at scaleThe top 3 challenges running multi-tenant Flink at scale
The top 3 challenges running multi-tenant Flink at scale
 
MongoDB vs. Postgres Benchmarks
MongoDB vs. Postgres Benchmarks MongoDB vs. Postgres Benchmarks
MongoDB vs. Postgres Benchmarks
 
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
 
Exactly-Once Financial Data Processing at Scale with Flink and Pinot
Exactly-Once Financial Data Processing at Scale with Flink and PinotExactly-Once Financial Data Processing at Scale with Flink and Pinot
Exactly-Once Financial Data Processing at Scale with Flink and Pinot
 
Pinot: Realtime OLAP for 530 Million Users - Sigmod 2018
Pinot: Realtime OLAP for 530 Million Users - Sigmod 2018Pinot: Realtime OLAP for 530 Million Users - Sigmod 2018
Pinot: Realtime OLAP for 530 Million Users - Sigmod 2018
 
Grafana Loki: like Prometheus, but for Logs
Grafana Loki: like Prometheus, but for LogsGrafana Loki: like Prometheus, but for Logs
Grafana Loki: like Prometheus, but for Logs
 
The Flux Capacitor of Kafka Streams and ksqlDB (Matthias J. Sax, Confluent) K...
The Flux Capacitor of Kafka Streams and ksqlDB (Matthias J. Sax, Confluent) K...The Flux Capacitor of Kafka Streams and ksqlDB (Matthias J. Sax, Confluent) K...
The Flux Capacitor of Kafka Streams and ksqlDB (Matthias J. Sax, Confluent) K...
 
Spark Operator—Deploy, Manage and Monitor Spark clusters on Kubernetes
 Spark Operator—Deploy, Manage and Monitor Spark clusters on Kubernetes Spark Operator—Deploy, Manage and Monitor Spark clusters on Kubernetes
Spark Operator—Deploy, Manage and Monitor Spark clusters on Kubernetes
 
Optimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performanceOptimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performance
 
Building a fully managed stream processing platform on Flink at scale for Lin...
Building a fully managed stream processing platform on Flink at scale for Lin...Building a fully managed stream processing platform on Flink at scale for Lin...
Building a fully managed stream processing platform on Flink at scale for Lin...
 
Demystifying flink memory allocation and tuning - Roshan Naik, Uber
Demystifying flink memory allocation and tuning - Roshan Naik, UberDemystifying flink memory allocation and tuning - Roshan Naik, Uber
Demystifying flink memory allocation and tuning - Roshan Naik, Uber
 
Practical learnings from running thousands of Flink jobs
Practical learnings from running thousands of Flink jobsPractical learnings from running thousands of Flink jobs
Practical learnings from running thousands of Flink jobs
 
[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기
 

Andere mochten auch

阿里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.
 

Andere mochten auch (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
 

Ähnlich wie High Performance Server Programming Tips

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
 

Ähnlich wie High Performance Server Programming Tips (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
 

Kürzlich hochgeladen

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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
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
 
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
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
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
 
[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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
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
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 

Kürzlich hochgeladen (20)

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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
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
 
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
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
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
 
[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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

High Performance Server Programming Tips

  • 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