SlideShare une entreprise Scribd logo
1  sur  35
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅NAVER D2
 
Apache kafka performance(throughput) - without data loss and guaranteeing dat...
Apache kafka performance(throughput) - without data loss and guaranteeing dat...Apache kafka performance(throughput) - without data loss and guaranteeing dat...
Apache kafka performance(throughput) - without data loss and guaranteeing dat...SANG WON PARK
 
YOW2021 Computing Performance
YOW2021 Computing PerformanceYOW2021 Computing Performance
YOW2021 Computing PerformanceBrendan Gregg
 
[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
 
A Journey into Hexagon: Dissecting Qualcomm Basebands
A Journey into Hexagon: Dissecting Qualcomm BasebandsA Journey into Hexagon: Dissecting Qualcomm Basebands
A Journey into Hexagon: Dissecting Qualcomm BasebandsPriyanka Aash
 
Security Monitoring with eBPF
Security Monitoring with eBPFSecurity Monitoring with eBPF
Security Monitoring with eBPFAlex Maestretti
 
Linux Linux Traffic Control
Linux Linux Traffic ControlLinux Linux Traffic Control
Linux Linux Traffic ControlSUSE Labs Taipei
 
Red Bend Software: Separation Using Type-1 Virtualization in Vehicles and Aut...
Red Bend Software: Separation Using Type-1 Virtualization in Vehicles and Aut...Red Bend Software: Separation Using Type-1 Virtualization in Vehicles and Aut...
Red Bend Software: Separation Using Type-1 Virtualization in Vehicles and Aut...Red Bend Software
 
Linux BPF Superpowers
Linux BPF SuperpowersLinux BPF Superpowers
Linux BPF SuperpowersBrendan Gregg
 
Openstack zun,virtual kubelet
Openstack zun,virtual kubeletOpenstack zun,virtual kubelet
Openstack zun,virtual kubeletChanyeol yoon
 
Linux Instrumentation
Linux InstrumentationLinux Instrumentation
Linux InstrumentationDarkStarSword
 
Velocity 2015 linux perf tools
Velocity 2015 linux perf toolsVelocity 2015 linux perf tools
Velocity 2015 linux perf toolsBrendan Gregg
 
Inside Android's UI
Inside Android's UIInside Android's UI
Inside Android's UIOpersys inc.
 
日本OpenStackユーザ会 第37回勉強会
日本OpenStackユーザ会 第37回勉強会日本OpenStackユーザ会 第37回勉強会
日本OpenStackユーザ会 第37回勉強会Yushiro Furukawa
 

Tendances (20)

[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅[232] 성능어디까지쥐어짜봤니 송태웅
[232] 성능어디까지쥐어짜봤니 송태웅
 
Apache kafka performance(throughput) - without data loss and guaranteeing dat...
Apache kafka performance(throughput) - without data loss and guaranteeing dat...Apache kafka performance(throughput) - without data loss and guaranteeing dat...
Apache kafka performance(throughput) - without data loss and guaranteeing dat...
 
YOW2021 Computing Performance
YOW2021 Computing PerformanceYOW2021 Computing Performance
YOW2021 Computing Performance
 
[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 구성 및 최적화
 
Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)
 
A Journey into Hexagon: Dissecting Qualcomm Basebands
A Journey into Hexagon: Dissecting Qualcomm BasebandsA Journey into Hexagon: Dissecting Qualcomm Basebands
A Journey into Hexagon: Dissecting Qualcomm Basebands
 
Embedded Android : System Development - Part III (Audio / Video HAL)
Embedded Android : System Development - Part III (Audio / Video HAL)Embedded Android : System Development - Part III (Audio / Video HAL)
Embedded Android : System Development - Part III (Audio / Video HAL)
 
Security Monitoring with eBPF
Security Monitoring with eBPFSecurity Monitoring with eBPF
Security Monitoring with eBPF
 
Embedded Virtualization for Mobile Devices
Embedded Virtualization for Mobile DevicesEmbedded Virtualization for Mobile Devices
Embedded Virtualization for Mobile Devices
 
Linux Linux Traffic Control
Linux Linux Traffic ControlLinux Linux Traffic Control
Linux Linux Traffic Control
 
Embedded Android : System Development - Part I
Embedded Android : System Development - Part IEmbedded Android : System Development - Part I
Embedded Android : System Development - Part I
 
Red Bend Software: Separation Using Type-1 Virtualization in Vehicles and Aut...
Red Bend Software: Separation Using Type-1 Virtualization in Vehicles and Aut...Red Bend Software: Separation Using Type-1 Virtualization in Vehicles and Aut...
Red Bend Software: Separation Using Type-1 Virtualization in Vehicles and Aut...
 
Linux BPF Superpowers
Linux BPF SuperpowersLinux BPF Superpowers
Linux BPF Superpowers
 
Openstack zun,virtual kubelet
Openstack zun,virtual kubeletOpenstack zun,virtual kubelet
Openstack zun,virtual kubelet
 
Linux Instrumentation
Linux InstrumentationLinux Instrumentation
Linux Instrumentation
 
Velocity 2015 linux perf tools
Velocity 2015 linux perf toolsVelocity 2015 linux perf tools
Velocity 2015 linux perf tools
 
Basic Linux Internals
Basic Linux InternalsBasic Linux Internals
Basic Linux Internals
 
Inside Android's UI
Inside Android's UIInside Android's UI
Inside Android's UI
 
Embedded Android : System Development - Part IV (Android System Services)
Embedded Android : System Development - Part IV (Android System Services)Embedded Android : System Development - Part IV (Android System Services)
Embedded Android : System Development - Part IV (Android System Services)
 
日本OpenStackユーザ会 第37回勉強会
日本OpenStackユーザ会 第37回勉強会日本OpenStackユーザ会 第37回勉強会
日本OpenStackユーザ会 第37回勉強会
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
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
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
"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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 

Dernier (20)

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
"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 ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 

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