SlideShare a Scribd company logo
1 of 51
Download to read offline
Lisp Meetup #22 Eitaro Fukamachi 
Writing 
a fast HTTP parser
Thank you for coming.
I’m Eitaro Fukamachi 
@nitro_idiot fukamachi
(and 'web-application-developer 
'common-lisper)
We’re hiring! 
Tell @Rudolph_Miller.
fast-http 
• HTTP request/response parser 
• Written in portable Common Lisp 
• Fast 
• Chunked body parser
fast-http 
Benchmarked with SBCL 1.2.5 / GCC v6.0.0
Let me tell 
why I had to write 
a fast HTTP parser.
Wookie is slower than Node.js 
• Wookie is 2 times slower than Node.js 
• Profiling result was saying 
“WOOKIE:READ-DATA” was pretty slow. 
• It was only calling “http-parse”. 
• “http-parse” which is an HTTP parser 
Wookie is using.
The bottleneck was 
HTTP parsing.
Wookie is slower than Node.js 
• Node.js’s HTTP parse is “http-parser”. 
• Written in C. 
• General version of Nginx’s HTTP parser. 
• Is it possible to beat it with Common Lisp?
Today, I’m talking 
what I did for writing 
a fast Common Lisp program.
5 important things 
• Architecture 
• Reducing memory allocation 
• Choosing the right data types 
• Benchmark & Profile 
• Type declarations
5 important things 
• Architecture 
• Reducing memory allocation 
• Choosing the right data types 
• Benchmark & Profile 
• Type declarations
A brief introduction of HTTP
HTTP request look like… 
GET /media HTTP/1.1↵ 
Host: somewrite.jp↵ 
Connection: keep-alive↵ 
Accept: */*↵ 
↵
HTTP request look like… 
GET /media HTTP/1.1↵ 
Host: somewrite.jp↵ 
Connection: keep-alive↵ 
Accept: */*↵ 
↵ 
First Line 
Headers 
Body (empty, in this case)
HTTP request look like… 
GET /media HTTP/1.1↵ 
Host: somewrite.jp↵ 
Connection: keep-alive↵ 
Accept: */*↵ 
↵ CR + LF 
CRLF * 2 at the end of headers
HTTP response look like… 
HTTP/1.1 200 OK↵ 
Cache-Control: max-age=0↵ 
Content-Type: text/html↵ 
Date: Wed, 26 Nov 2014 04:52:55 GMT↵ 
↵ 
<html> 
…
HTTP response look like… 
HTTP/1.1 200 OK↵ 
Status Line 
Cache-Control: max-age=0↵ 
Content-Type: text/html↵ 
Headers 
Date: Wed, 26 Nov 2014 04:52:55 GMT↵ 
↵ 
<html> 
… 
Body
HTTP is… 
• Text-based protocol. (not binary) 
• Lines terminated with CRLF 
• Very lenient. 
• Ignore multiple spaces 
• Allow continuous header values
And, 
there’s another difficulty.
HTTP messages are 
sent over a network.
Which means, 
we need to think about 
long & incomplete 
HTTP messages.
There’s 2 ways 
to resolve this problem.
1. Stateful (http-parser)
http-parser (used in Node.js) 
• https://github.com/joyent/http-parser 
• Written in C 
• Ported from Nginx’s HTTP parser 
• Written as Node.js’s HTTP parser 
• Stateful
http-parser (used in Node.js) 
for (p=data; p != data + len; p++) { 
… 
switch (parser->state) { 
case s_dead: 
… 
case s_start_req_or_res: 
… 
case s_res_or_resp_H: 
… 
} 
}
http-parser (used in Node.js) 
for (p=data; p != data + len; p++) { 
… 
switch (parser->state) { 
Process char by char 
case s_dead: 
… 
case s_start_req_or_res: 
… 
case s_res_or_resp_H: 
… 
} 
} 
Do something 
for each state
2. Stateless (PicoHTTPParser)
PicoHTTPParser (used in H2O) 
• https://github.com/h2o/picohttpparser 
• Written in C 
• Stateless 
• Reparse when the data is incomplete 
• Most HTTP request is small
And fast-http is…
fast-http is in the middle 
• Not track state for every character 
• Set state for every line 
• It makes the program simple 
• And easy to optimize
5 important things 
• Architecture 
• Reducing memory allocation 
• Choosing the right data types 
• Benchmark & Profile 
• Type declarations
Memory allocation is slow 
• (in general) 
• Make sure not to allocate memory during 
processing 
• cons, make-instance, make-array… 
• subseq, append, copy-seq
5 important things 
• Architecture 
• Reducing memory allocation 
• Choosing the right data types 
• Benchmark & Profile 
• Type declarations
Data types 
• Wrong data type makes your program slow. 
• List or Vector 
• Hash Table or Structure or Class
5 important things 
• Architecture 
• Reducing memory allocation 
• Choosing the right data types 
• Benchmark & Profile 
• Type declarations
Benchmark is quite important 
• “Don’t guess, measure!” 
• Check if your changes improve the 
performance. 
• Benchmarking also keeps your motivation.
Profiling 
• SBCL has builtin profiler 
• (sb-profile:profile “FAST-HTTP” …) 
• (sb-profile:report)
5 important things 
• Architecture 
• Reducing memory allocation 
• Choosing the right data types 
• Benchmark & Profile 
• Type declarations
Type declaration 
• Common Lisp has type declaration 
(optional) 
• (declare (type <type> <variable symbol>)) 
• It’s a hint for your Lisp compiler 
• (declare (optimize (speed 3) (safety 0))) 
• It’s your wish to your Lisp compiler 
See also: Cより高速なCommon Lispコードを書く
(safety 0) 
• (safety 0) means “don’t check the type & 
array index in run-time”. 
• Fast & unsafe (like C) 
• Is fixnum enough? 
• What do you do when someone passes a 
bignum to the function?
(safety 0) 
• fast-http has 2 layers 
• Low-level API 
• (speed 3) (safety 0) 
• High-level API (safer) 
• Check the variable type 
• (speed 3) (safety 2)
Attitude
Attitude 
• Write carefully. 
• It’s possible to beat C program 
• (if the program is complicated enough) 
• Don’t give up easily 
• Safety is more important than speed
Thanks.
EITARO FUKAMACHI 
8arrow.org 
@nitro_idiot fukamachi

More Related Content

What's hot

C#×LLVM=アセンブラ!? 〜詳説・Burstコンパイラー〜
C#×LLVM=アセンブラ!? 〜詳説・Burstコンパイラー〜C#×LLVM=アセンブラ!? 〜詳説・Burstコンパイラー〜
C#×LLVM=アセンブラ!? 〜詳説・Burstコンパイラー〜UnityTechnologiesJapan002
 
[NDC16] Effective Git
[NDC16] Effective Git[NDC16] Effective Git
[NDC16] Effective GitChanwoong Kim
 
macOSの仮想化技術について ~Virtualization-rs Rust bindings for virtualization.framework ~
macOSの仮想化技術について ~Virtualization-rs Rust bindings for virtualization.framework ~macOSの仮想化技術について ~Virtualization-rs Rust bindings for virtualization.framework ~
macOSの仮想化技術について ~Virtualization-rs Rust bindings for virtualization.framework ~NTT Communications Technology Development
 
C/C++プログラマのための開発ツール
C/C++プログラマのための開発ツールC/C++プログラマのための開発ツール
C/C++プログラマのための開発ツールMITSUNARI Shigeo
 
Quine・難解プログラミングについて
Quine・難解プログラミングについてQuine・難解プログラミングについて
Quine・難解プログラミングについてmametter
 
How to read linux kernel
How to read linux kernelHow to read linux kernel
How to read linux kernelNaoya Ito
 
Boost UDP Transaction Performance
Boost UDP Transaction PerformanceBoost UDP Transaction Performance
Boost UDP Transaction PerformanceLF Events
 
Yoctoで綺麗なkernel configを作る
Yoctoで綺麗なkernel configを作るYoctoで綺麗なkernel configを作る
Yoctoで綺麗なkernel configを作るshimadah
 
Windows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCPWindows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCPSeungmo Koo
 
A whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizerA whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizerNikita Popov
 
MAP 実装してみた
MAP 実装してみたMAP 実装してみた
MAP 実装してみたMasakazu Asama
 
使用 Pytest 進行單元測試 (PyCon TW 2021)
使用 Pytest 進行單元測試 (PyCon TW 2021)使用 Pytest 進行單元測試 (PyCon TW 2021)
使用 Pytest 進行單元測試 (PyCon TW 2021)Max Lai
 
Debugging concurrency programs in go
Debugging concurrency programs in goDebugging concurrency programs in go
Debugging concurrency programs in goAndrii Soldatenko
 

What's hot (20)

C#×LLVM=アセンブラ!? 〜詳説・Burstコンパイラー〜
C#×LLVM=アセンブラ!? 〜詳説・Burstコンパイラー〜C#×LLVM=アセンブラ!? 〜詳説・Burstコンパイラー〜
C#×LLVM=アセンブラ!? 〜詳説・Burstコンパイラー〜
 
SSH力をつけよう
SSH力をつけようSSH力をつけよう
SSH力をつけよう
 
[NDC16] Effective Git
[NDC16] Effective Git[NDC16] Effective Git
[NDC16] Effective Git
 
macOSの仮想化技術について ~Virtualization-rs Rust bindings for virtualization.framework ~
macOSの仮想化技術について ~Virtualization-rs Rust bindings for virtualization.framework ~macOSの仮想化技術について ~Virtualization-rs Rust bindings for virtualization.framework ~
macOSの仮想化技術について ~Virtualization-rs Rust bindings for virtualization.framework ~
 
【HITCON FreeTalk】Supply Chain Attack
【HITCON FreeTalk】Supply Chain Attack【HITCON FreeTalk】Supply Chain Attack
【HITCON FreeTalk】Supply Chain Attack
 
淺談探索 Linux 系統設計之道
淺談探索 Linux 系統設計之道 淺談探索 Linux 系統設計之道
淺談探索 Linux 系統設計之道
 
レシピの作り方入門
レシピの作り方入門レシピの作り方入門
レシピの作り方入門
 
C/C++プログラマのための開発ツール
C/C++プログラマのための開発ツールC/C++プログラマのための開発ツール
C/C++プログラマのための開発ツール
 
Quine・難解プログラミングについて
Quine・難解プログラミングについてQuine・難解プログラミングについて
Quine・難解プログラミングについて
 
How to read linux kernel
How to read linux kernelHow to read linux kernel
How to read linux kernel
 
Boost UDP Transaction Performance
Boost UDP Transaction PerformanceBoost UDP Transaction Performance
Boost UDP Transaction Performance
 
Yoctoで綺麗なkernel configを作る
Yoctoで綺麗なkernel configを作るYoctoで綺麗なkernel configを作る
Yoctoで綺麗なkernel configを作る
 
Windows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCPWindows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCP
 
A whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizerA whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizer
 
WebSocket / WebRTCの技術紹介
WebSocket / WebRTCの技術紹介WebSocket / WebRTCの技術紹介
WebSocket / WebRTCの技術紹介
 
MAP 実装してみた
MAP 実装してみたMAP 実装してみた
MAP 実装してみた
 
使用 Pytest 進行單元測試 (PyCon TW 2021)
使用 Pytest 進行單元測試 (PyCon TW 2021)使用 Pytest 進行單元測試 (PyCon TW 2021)
使用 Pytest 進行單元測試 (PyCon TW 2021)
 
What Can Compilers Do for Us?
What Can Compilers Do for Us?What Can Compilers Do for Us?
What Can Compilers Do for Us?
 
GDB Rocks!
GDB Rocks!GDB Rocks!
GDB Rocks!
 
Debugging concurrency programs in go
Debugging concurrency programs in goDebugging concurrency programs in go
Debugging concurrency programs in go
 

Similar to Writing a fast HTTP parser

Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015fukamachi
 
A Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakA Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakSoroush Dalili
 
Messaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new frameworkMessaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new frameworkTomas Doran
 
Http2 Security Perspective
Http2 Security PerspectiveHttp2 Security Perspective
Http2 Security PerspectiveSunil Kumar
 
Adding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemAdding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemJohn Efstathiades
 
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilitiesVorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilitiesDefconRussia
 
How to Write the Fastest JSON Parser/Writer in the World
How to Write the Fastest JSON Parser/Writer in the WorldHow to Write the Fastest JSON Parser/Writer in the World
How to Write the Fastest JSON Parser/Writer in the WorldMilo Yip
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourSoroush Dalili
 
Http - All you need to know
Http - All you need to knowHttp - All you need to know
Http - All you need to knowGökhan Şengün
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
12 Step Guide to Lotuscript
12 Step Guide to Lotuscript12 Step Guide to Lotuscript
12 Step Guide to LotuscriptBill Buchan
 
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)Ontico
 
Stack Exchange Infrastructure - LISA 14
Stack Exchange Infrastructure - LISA 14Stack Exchange Infrastructure - LISA 14
Stack Exchange Infrastructure - LISA 14GABeech
 
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangPractical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangLyon Yang
 
Kubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd について
Kubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd についてKubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd について
Kubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd についてLINE Corporation
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTPMykhailo Kolesnyk
 

Similar to Writing a fast HTTP parser (20)

Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015
 
A Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakA Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility Cloak
 
Http2 in practice
Http2 in practiceHttp2 in practice
Http2 in practice
 
Messaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new frameworkMessaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new framework
 
Http2 Security Perspective
Http2 Security PerspectiveHttp2 Security Perspective
Http2 Security Perspective
 
Adding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemAdding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded System
 
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilitiesVorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
 
Top ten-list
Top ten-listTop ten-list
Top ten-list
 
How to Write the Fastest JSON Parser/Writer in the World
How to Write the Fastest JSON Parser/Writer in the WorldHow to Write the Fastest JSON Parser/Writer in the World
How to Write the Fastest JSON Parser/Writer in the World
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
 
computer networking
computer networkingcomputer networking
computer networking
 
Http - All you need to know
Http - All you need to knowHttp - All you need to know
Http - All you need to know
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
12 Step Guide to Lotuscript
12 Step Guide to Lotuscript12 Step Guide to Lotuscript
12 Step Guide to Lotuscript
 
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
 
Stack Exchange Infrastructure - LISA 14
Stack Exchange Infrastructure - LISA 14Stack Exchange Infrastructure - LISA 14
Stack Exchange Infrastructure - LISA 14
 
Scalable Web Apps
Scalable Web AppsScalable Web Apps
Scalable Web Apps
 
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangPractical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
 
Kubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd について
Kubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd についてKubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd について
Kubernetes上で動作する機械学習モジュールの配信&管理基盤Rekcurd について
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTP
 

More from fukamachi

競プロの話
競プロの話競プロの話
競プロの話fukamachi
 
Rove / Testing is a pity in Common Lisp
Rove / Testing is a pity in Common LispRove / Testing is a pity in Common Lisp
Rove / Testing is a pity in Common Lispfukamachi
 
Building GUI App with Electron and Lisp
Building GUI App with Electron and LispBuilding GUI App with Electron and Lisp
Building GUI App with Electron and Lispfukamachi
 
Mito, a successor of Integral
Mito, a successor of IntegralMito, a successor of Integral
Mito, a successor of Integralfukamachi
 
Dexador Rises
Dexador RisesDexador Rises
Dexador Risesfukamachi
 
Clack: glue for web apps
Clack: glue for web appsClack: glue for web apps
Clack: glue for web appsfukamachi
 
Woo: Writing a fast web server
Woo: Writing a fast web serverWoo: Writing a fast web server
Woo: Writing a fast web serverfukamachi
 
Redesigning Common Lisp
Redesigning Common LispRedesigning Common Lisp
Redesigning Common Lispfukamachi
 
Integral - New O/R Mapper for Common Lisp
Integral - New O/R Mapper for Common LispIntegral - New O/R Mapper for Common Lisp
Integral - New O/R Mapper for Common Lispfukamachi
 
第四回関西Emacs「ari.el」
第四回関西Emacs「ari.el」第四回関西Emacs「ari.el」
第四回関西Emacs「ari.el」fukamachi
 
Clack & Caveman
Clack & CavemanClack & Caveman
Clack & Cavemanfukamachi
 
Lispで仕事をするために
Lispで仕事をするためにLispで仕事をするために
Lispで仕事をするためにfukamachi
 
Lisperの見る世界
Lisperの見る世界Lisperの見る世界
Lisperの見る世界fukamachi
 
JavaからClojure、そして夢の世界へ
JavaからClojure、そして夢の世界へJavaからClojure、そして夢の世界へ
JavaからClojure、そして夢の世界へfukamachi
 
自分をClojure化する方法
自分をClojure化する方法自分をClojure化する方法
自分をClojure化する方法fukamachi
 
Google App Engine for Java (手嶋屋勉強会)
Google App Engine for Java (手嶋屋勉強会)Google App Engine for Java (手嶋屋勉強会)
Google App Engine for Java (手嶋屋勉強会)fukamachi
 

More from fukamachi (20)

競プロの話
競プロの話競プロの話
競プロの話
 
Rove / Testing is a pity in Common Lisp
Rove / Testing is a pity in Common LispRove / Testing is a pity in Common Lisp
Rove / Testing is a pity in Common Lisp
 
Building GUI App with Electron and Lisp
Building GUI App with Electron and LispBuilding GUI App with Electron and Lisp
Building GUI App with Electron and Lisp
 
SBLint
SBLintSBLint
SBLint
 
Mito, a successor of Integral
Mito, a successor of IntegralMito, a successor of Integral
Mito, a successor of Integral
 
Dexador Rises
Dexador RisesDexador Rises
Dexador Rises
 
Clack: glue for web apps
Clack: glue for web appsClack: glue for web apps
Clack: glue for web apps
 
Woo: Writing a fast web server
Woo: Writing a fast web serverWoo: Writing a fast web server
Woo: Writing a fast web server
 
Redesigning Common Lisp
Redesigning Common LispRedesigning Common Lisp
Redesigning Common Lisp
 
Integral - New O/R Mapper for Common Lisp
Integral - New O/R Mapper for Common LispIntegral - New O/R Mapper for Common Lisp
Integral - New O/R Mapper for Common Lisp
 
About Clack
About ClackAbout Clack
About Clack
 
Shelly
ShellyShelly
Shelly
 
第四回関西Emacs「ari.el」
第四回関西Emacs「ari.el」第四回関西Emacs「ari.el」
第四回関西Emacs「ari.el」
 
Clack & Caveman
Clack & CavemanClack & Caveman
Clack & Caveman
 
Lispで仕事をするために
Lispで仕事をするためにLispで仕事をするために
Lispで仕事をするために
 
Lisperの見る世界
Lisperの見る世界Lisperの見る世界
Lisperの見る世界
 
Lisp Poetry
Lisp PoetryLisp Poetry
Lisp Poetry
 
JavaからClojure、そして夢の世界へ
JavaからClojure、そして夢の世界へJavaからClojure、そして夢の世界へ
JavaからClojure、そして夢の世界へ
 
自分をClojure化する方法
自分をClojure化する方法自分をClojure化する方法
自分をClojure化する方法
 
Google App Engine for Java (手嶋屋勉強会)
Google App Engine for Java (手嶋屋勉強会)Google App Engine for Java (手嶋屋勉強会)
Google App Engine for Java (手嶋屋勉強会)
 

Recently uploaded

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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
 
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
 
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
 
[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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
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
 
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
 
[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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Writing a fast HTTP parser

  • 1. Lisp Meetup #22 Eitaro Fukamachi Writing a fast HTTP parser
  • 2. Thank you for coming.
  • 3. I’m Eitaro Fukamachi @nitro_idiot fukamachi
  • 5.
  • 6.
  • 7. We’re hiring! Tell @Rudolph_Miller.
  • 8. fast-http • HTTP request/response parser • Written in portable Common Lisp • Fast • Chunked body parser
  • 9. fast-http Benchmarked with SBCL 1.2.5 / GCC v6.0.0
  • 10. Let me tell why I had to write a fast HTTP parser.
  • 11.
  • 12. Wookie is slower than Node.js • Wookie is 2 times slower than Node.js • Profiling result was saying “WOOKIE:READ-DATA” was pretty slow. • It was only calling “http-parse”. • “http-parse” which is an HTTP parser Wookie is using.
  • 13. The bottleneck was HTTP parsing.
  • 14. Wookie is slower than Node.js • Node.js’s HTTP parse is “http-parser”. • Written in C. • General version of Nginx’s HTTP parser. • Is it possible to beat it with Common Lisp?
  • 15. Today, I’m talking what I did for writing a fast Common Lisp program.
  • 16. 5 important things • Architecture • Reducing memory allocation • Choosing the right data types • Benchmark & Profile • Type declarations
  • 17. 5 important things • Architecture • Reducing memory allocation • Choosing the right data types • Benchmark & Profile • Type declarations
  • 19. HTTP request look like… GET /media HTTP/1.1↵ Host: somewrite.jp↵ Connection: keep-alive↵ Accept: */*↵ ↵
  • 20. HTTP request look like… GET /media HTTP/1.1↵ Host: somewrite.jp↵ Connection: keep-alive↵ Accept: */*↵ ↵ First Line Headers Body (empty, in this case)
  • 21. HTTP request look like… GET /media HTTP/1.1↵ Host: somewrite.jp↵ Connection: keep-alive↵ Accept: */*↵ ↵ CR + LF CRLF * 2 at the end of headers
  • 22. HTTP response look like… HTTP/1.1 200 OK↵ Cache-Control: max-age=0↵ Content-Type: text/html↵ Date: Wed, 26 Nov 2014 04:52:55 GMT↵ ↵ <html> …
  • 23. HTTP response look like… HTTP/1.1 200 OK↵ Status Line Cache-Control: max-age=0↵ Content-Type: text/html↵ Headers Date: Wed, 26 Nov 2014 04:52:55 GMT↵ ↵ <html> … Body
  • 24. HTTP is… • Text-based protocol. (not binary) • Lines terminated with CRLF • Very lenient. • Ignore multiple spaces • Allow continuous header values
  • 25. And, there’s another difficulty.
  • 26. HTTP messages are sent over a network.
  • 27. Which means, we need to think about long & incomplete HTTP messages.
  • 28. There’s 2 ways to resolve this problem.
  • 30. http-parser (used in Node.js) • https://github.com/joyent/http-parser • Written in C • Ported from Nginx’s HTTP parser • Written as Node.js’s HTTP parser • Stateful
  • 31. http-parser (used in Node.js) for (p=data; p != data + len; p++) { … switch (parser->state) { case s_dead: … case s_start_req_or_res: … case s_res_or_resp_H: … } }
  • 32. http-parser (used in Node.js) for (p=data; p != data + len; p++) { … switch (parser->state) { Process char by char case s_dead: … case s_start_req_or_res: … case s_res_or_resp_H: … } } Do something for each state
  • 34. PicoHTTPParser (used in H2O) • https://github.com/h2o/picohttpparser • Written in C • Stateless • Reparse when the data is incomplete • Most HTTP request is small
  • 36. fast-http is in the middle • Not track state for every character • Set state for every line • It makes the program simple • And easy to optimize
  • 37. 5 important things • Architecture • Reducing memory allocation • Choosing the right data types • Benchmark & Profile • Type declarations
  • 38. Memory allocation is slow • (in general) • Make sure not to allocate memory during processing • cons, make-instance, make-array… • subseq, append, copy-seq
  • 39. 5 important things • Architecture • Reducing memory allocation • Choosing the right data types • Benchmark & Profile • Type declarations
  • 40. Data types • Wrong data type makes your program slow. • List or Vector • Hash Table or Structure or Class
  • 41. 5 important things • Architecture • Reducing memory allocation • Choosing the right data types • Benchmark & Profile • Type declarations
  • 42. Benchmark is quite important • “Don’t guess, measure!” • Check if your changes improve the performance. • Benchmarking also keeps your motivation.
  • 43. Profiling • SBCL has builtin profiler • (sb-profile:profile “FAST-HTTP” …) • (sb-profile:report)
  • 44. 5 important things • Architecture • Reducing memory allocation • Choosing the right data types • Benchmark & Profile • Type declarations
  • 45. Type declaration • Common Lisp has type declaration (optional) • (declare (type <type> <variable symbol>)) • It’s a hint for your Lisp compiler • (declare (optimize (speed 3) (safety 0))) • It’s your wish to your Lisp compiler See also: Cより高速なCommon Lispコードを書く
  • 46. (safety 0) • (safety 0) means “don’t check the type & array index in run-time”. • Fast & unsafe (like C) • Is fixnum enough? • What do you do when someone passes a bignum to the function?
  • 47. (safety 0) • fast-http has 2 layers • Low-level API • (speed 3) (safety 0) • High-level API (safer) • Check the variable type • (speed 3) (safety 2)
  • 49. Attitude • Write carefully. • It’s possible to beat C program • (if the program is complicated enough) • Don’t give up easily • Safety is more important than speed
  • 51. EITARO FUKAMACHI 8arrow.org @nitro_idiot fukamachi