{"id":13513458,"url":"https://github.com/boazsegev/iodine","last_synced_at":"2025-04-29T18:44:44.090Z","repository":{"id":38711094,"uuid":"44454577","full_name":"boazsegev/iodine","owner":"boazsegev","description":"iodine - HTTP / WebSockets Server for Ruby with Pub/Sub support","archived":false,"fork":false,"pushed_at":"2025-04-15T07:27:46.000Z","size":7587,"stargazers_count":936,"open_issues_count":22,"forks_count":52,"subscribers_count":26,"default_branch":"master","last_synced_at":"2025-04-15T08:44:57.025Z","etag":null,"topics":["clustering","high-performance","http","message-bus","multithreading","pubsub","ruby","server","sse","web-server","websocket"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/boazsegev.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2015-10-17T21:04:41.000Z","updated_at":"2025-04-12T07:53:33.000Z","dependencies_parsed_at":"2023-12-19T04:13:21.530Z","dependency_job_id":"556321a0-3a5b-447e-95a9-115414e21c52","html_url":"https://github.com/boazsegev/iodine","commit_stats":{"total_commits":1365,"total_committers":25,"mean_commits":54.6,"dds":0.3831501831501831,"last_synced_commit":"db9e43a07b71745bd470c77d26f3d0f78bc4f257"},"previous_names":[],"tags_count":137,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/boazsegev%2Fiodine","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/boazsegev%2Fiodine/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/boazsegev%2Fiodine/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/boazsegev%2Fiodine/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/boazsegev","download_url":"https://codeload.github.com/boazsegev/iodine/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251562169,"owners_count":21609506,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["clustering","high-performance","http","message-bus","multithreading","pubsub","ruby","server","sse","web-server","websocket"],"created_at":"2024-08-01T05:00:26.479Z","updated_at":"2025-04-29T18:44:44.067Z","avatar_url":"https://github.com/boazsegev.png","language":"C","funding_links":[],"categories":["C","Tools per Language","Web Servers"],"sub_categories":["Ruby"],"readme":"# iodine - Why Settle for a fast HTTP / WebSocket Server with native Pub/Sub?\n\n[![Gem](https://img.shields.io/gem/dt/iodine.svg)](https://rubygems.org/gems/iodine)\n[![Build Status](https://github.com/boazsegev/iodine/actions/workflows/ruby.yml/badge.svg)](https://github.com/boazsegev/iodine/actions/workflows/ruby.yml)\n[![Gem Version](https://badge.fury.io/rb/iodine.svg)](https://badge.fury.io/rb/iodine)\n[![Inline docs](http://inch-ci.org/github/boazsegev/iodine.svg?branch=master)](http://www.rubydoc.info/github/boazsegev/iodine/master/frames)\n[![GitHub](https://img.shields.io/badge/GitHub-Open%20Source-blue.svg)](https://github.com/boazsegev/iodine)\n\n[![Logo](https://github.com/boazsegev/iodine/raw/master/logo.png)](https://github.com/boazsegev/iodine)\n\nIodine is a fast concurrent web application server for real-time Ruby applications, with native support for WebSockets and Pub/Sub services - but it's also so much more.\n\nIodine is a Ruby wrapper for much of the [facil.io](https://facil.io) C framework, leveraging the speed of C for many common web application tasks. In addition, iodine abstracts away all network concerns, so you never need to worry about the transport layer, leaving you free to concentrate on your application logic.\n\nIodine includes native support for:\n\n* HTTP, WebSockets and EventSource (SSE) Services (server);\n* WebSocket connections (server / client);\n* Pub/Sub (with optional Redis Pub/Sub scaling);\n* Fast(!) builtin Mustache templating;\n* Static file service (with automatic `gzip` support for pre-compressed assets);\n* Optimized Logging to `stderr`;\n* Asynchronous event scheduling and timers;\n* HTTP/1.1 keep-alive and pipelining;\n* Heap Fragmentation Protection;\n* TLS 1.2 and above (Requiring OpenSSL \u003e= 1.1.0);\n* TCP/IP server and client connectivity;\n* Unix Socket server and client connectivity;\n* Hot Restarts (using the USR1 signal and without hot deployment);\n* Custom protocol authoring;\n* [Sequel](https://github.com/jeremyevans/sequel) and ActiveRecord forking protection;\n* and more!\n\nSince iodine wraps much of the [C facil.io framework](https://github.com/boazsegev/facil.io) for Ruby:\n\n* Iodine can handle **thousands of concurrent connections** (tested with more than 20K connections on Linux)!\n\n* Iodine is ideal for **Linux/Unix** based systems (i.e. macOS, Ubuntu, FreeBSD etc'), which are ideal for evented IO (while Windows and Solaris are better at IO *completion* events, which are very different).\n\nIodine is a C extension for Ruby, developed and optimized for Ruby MRI 2.3 and up... it should support the whole Ruby 2.x and 3.x MRI family, but CI tests start at Ruby 2.3.\n\n**Note**: iodine does **not** support streaming when using Rack. It's recommended to avoid blocking the server when using `body.each` since the `each` loop will block  iodine's thread until it's finished and iodine won't send any data before the loop is done.\n\n## Iodine - a fast \u0026 powerful HTTP + WebSockets server with native Pub/Sub\n\nIodine includes a light and fast HTTP and Websocket server written in C that was written according to the [Rack interface specifications](http://www.rubydoc.info/github/rack/rack/master/file/SPEC) and the [Websocket draft extension](./SPEC-Websocket-Draft.md).\n\nWith `Iodine.listen service: :http` it's possible to run multiple HTTP applications (but please remember not to set more than a single application on a single TCP/IP port).\n\nIodine also supports native process cluster Pub/Sub and a native RedisEngine to easily scale iodine's Pub/Sub horizontally.\n\n### Known Issues and Reporting Issues\n\nSee the [GitHub Open Issues](https://github.com/boazsegev/iodine/issues) list for known issues and to report new issues.\n\n### Installing and Running Iodine\n\nInstall iodine on any Linux / BSD / macOS system using:\n\n```bash\ngem install iodine\n```\n\nUsing the iodine server is easy, simply add iodine as a gem to your Rails / Sinatra / Rack application's `Gemfile`:\n\n```ruby\ngem 'iodine', '~\u003e0.7'\n```\n\nThen start your application from the command-line / terminal using iodine:\n\n```bash\nbundler exec iodine\n```\n\n#### Installing with SSL/TLS\n\n**Note**: iodine has known issues with the TLS/SSL support. TLS/SSL should **NOT** be used in production (see issues #95 and #94).\n\nMake sure to update OpenSSL to the latest version **before installing Ruby** (`rbenv` should do this automatically).\n\nTo avoid name resolution conflicts, iodine will bind to the same OpenSSL version Ruby is bound to. To use SSL/TLS this should be OpenSSL \u003e= 1.1.0 or LibreSSL \u003e= 2.7.4.\n\nVerbose installation should provide a confirmation message, such as:\n\n```bash\n$ gem install iodine -f -V\n...\nchecking for -lcrypto... yes\nchecking for -lssl... yes\nDetected OpenSSL library, testing for version.\nConfirmed OpenSSL to be version 1.1.0 or above (OpenSSL 1.1.0j  20 Nov 2018)...\n* Compiling with HAVE_OPENSSL.\n...\n```\n\nThe installation script tests for OpenSSL 1.1.0 and above. However, this testing approach sometimes provides false positives. **If TLS isn't required, install with `NO_SSL=1`**. i.e.:\n\n```bash\nNO_SSL=1 bundler exec iodine\n```\n\n### Running with Rails\n\nOn Rails:\n\n1. Replace the `puma` gem with the `iodine` gem.\n\n1. Remove the `config/puma.rb` file (or comment out the code).\n\n1. Optionally, it's possible to add a `config/initializers/iodine.rb` file. For example:\n\n    ```ruby\n    # Iodine setup - use conditional setup to allow command-line arguments to override these:\n    if(defined?(Iodine))\n      Iodine.threads = ENV.fetch(\"RAILS_MAX_THREADS\", 5).to_i if Iodine.threads.zero?\n      Iodine.workers = ENV.fetch(\"WEB_CONCURRENCY\", 2).to_i if Iodine.workers.zero?\n      Iodine::DEFAULT_SETTINGS[:port] ||= ENV.fetch(\"PORT\") if ENV.fetch(\"PORT\")\n    end\n    ```\n\nWhen using native WebSockets with Rails, middle-ware is probably the best approach. A guide for this approach will, hopefully, get published in the future.\n\n**Note**: command-line instructions (CLI) should be the preferred way for configuring iodine, allowing for code-less configuration updates.\n\n### Optimizing Iodine's Concurrency\n\nTo get the most out of iodine, consider the amount of CPU cores available and the concurrency level the application requires.\n\nIodine will calculate, when possible, a good enough default concurrency model for fast applications. See if this works for your application or customize according to the application's needs.\n\nCommand line arguments allow easy access to different options, including concurrency levels. i.e., to set up 16 threads and 4 processes:\n\n```bash\nbundler exec iodine -p $PORT -t 16 -w 4\n```\n\nThe environment variables `THREADS` and `WORKERS` are automatically recognized when iodine is first required, allowing environment specific customization. i.e.:\n\n```bash\nexport THREADS=16\nexport WORKERS=-1 # negative values are fractions of CPU cores.\nbundler exec iodine -p $PORT\n```\n\nNegative values are evaluated as \"CPU Cores / abs(Value)\". i.e., on an 8 core CPU machine, this will produce 4 worker processes with 2 threads per worker:\n\n```bash\nbundler exec iodine -p $PORT -t 2 -w -2\n```\n\n### Heap Fragmentation Protection\n\nIodine includes a fast, network oriented, custom memory allocator, optimizing away some of the work usually placed on the Ruby Garbage Collector (GC).\n\nThis approach helps to minimize heap fragmentation for long running processes, by grouping many short-lived objects into a common memory space.\n\nIt is still recommended to consider [jemalloc](http://jemalloc.net) or other allocators that also help mitigate heap fragmentation issues.\n\n### Static file serving support\n\nIodine supports an internal static file service that bypasses the Ruby layer  and serves static files directly from \"C-land\".\n\nThis means that iodine won't lock Ruby's GVL when sending static files. The files will be sent directly, allowing for true native concurrency.\n\nSince the Ruby layer is unaware of these requests, logging can be performed by turning iodine's logger on.\n\nTo use native static file service, setup the public folder's address **before** starting the server.\n\nThis can be done when starting the server from the command line:\n\n```bash\nbundler exec iodine -p $PORT -t 16 -w 4 -www /my/public/folder\n```\n\nOr using a simple Ruby script. i.e. (a `my_server.rb` example):\n\n```ruby\nrequire 'iodine'\n# static file service\nIodine.listen, service: :http, public: '/my/public/folder'\n# for static file service, we only need a single thread and a single worker.\nIodine.threads = 1\nIodine.start\n```\n\nTo enable logging from the command line, use the `-v` (verbose) option:\n\n```bash\nbundler exec iodine -p $PORT -t 16 -w 4 -www /my/public/folder -v\n```\n\n#### X-Sendfile\n\nWhen a public folder is assigned (the static file server is active), iodine automatically adds support for the `X-Sendfile` header in any Ruby application response.\n\nThis allows Ruby to send very large files using a very small memory footprint and usually leverages the `sendfile` system call.\n\ni.e. (example `config.ru` for iodine):\n\n```ruby\napp = proc do |env|\n  request = Rack::Request.new(env)\n  if request.path_info == '/source'.freeze\n    [200, { 'X-Sendfile' =\u003e File.expand_path(__FILE__), 'Content-Type' =\u003e 'text/plain'}, []]\n  elsif request.path_info == '/file'.freeze\n    [200, { 'X-Header' =\u003e 'This was a Rack::Sendfile response sent as text.' }, File.open(__FILE__)]\n  else\n    [200, { 'Content-Type' =\u003e 'text/html',\n            'Content-Length' =\u003e request.path_info.length.to_s },\n     [request.path_info]]\n end\nend\n# # optional:\n# use Rack::Sendfile\nrun app\n```\n\nBenchmark [localhost:3000/source](http://localhost:3000/source) to experience the `X-Sendfile` extension at work.\n\n#### Pre-Compressed assets / files\n\nRails does this automatically when compiling assets, which is: `gzip` your static files.\n\nIodine will automatically recognize and send the `gz` version if the client (browser) supports the `gzip` transfer-encoding.\n\nFor example, to offer a compressed version of `style.css`, run (in the terminal):\n\n```bash\n$  gzip -k -9 style.css\n```\n\nThis results in both files, `style.css` (the original) and `style.css.gz` (the compressed).\n\nWhen a browser that supports compressed encoding (which is most browsers) requests the file, iodine will recognize that a pre-compressed option exists and will prefer the `gzip` compressed version.\n\nIt's as easy as that. No extra code required.\n\n### Special HTTP `Upgrade` and SSE support\n\nIodine's HTTP server implements the [WebSocket/SSE Rack Specification Draft](SPEC-Websocket-Draft.md), supporting native WebSocket/SSE connections using Rack's `env` Hash.\n\nThis promotes separation of concerns, where iodine handles all the Network related logic and the application can focus on the API and data it provides.\n\nUpgrading an HTTP connection can be performed either using iodine's native WebSocket / EventSource (SSE) support with `env['rack.upgrade?']` or by implementing your own protocol directly over the TCP/IP layer - be it a WebSocket flavor or something completely different - using `env['upgrade.tcp']`.\n\n#### EventSource / SSE\n\nIodine treats EventSource / SSE connections as if they were a half-duplex WebSocket connection, using the exact same API and callbacks as WebSockets.\n\nWhen an EventSource / SSE request is received, iodine will set the Rack Hash's upgrade property to `:sse`, so that: `env['rack.upgrade?'] == :sse`.\n\nThe rest is detailed in the WebSocket support section.\n\n#### WebSockets\n\nWhen a WebSocket connection request is received, iodine will set the Rack Hash's upgrade property to `:websocket`, so that: `env['rack.upgrade?'] == :websocket`\n\nTo \"upgrade\" the HTTP request to the WebSockets protocol (or SSE), simply provide iodine with a WebSocket Callback Object instance or class: `env['rack.upgrade'] = MyWebsocketClass` or `env['rack.upgrade'] = MyWebsocketClass.new(args)`\n\nIodine will adopt the object, providing it with network functionality (methods such as `write`, `defer` and `close` will become available) and invoke it's callbacks on network events.\n\nHere is a simple chat-room example we can run in the terminal (`irb`) or easily paste into a `config.ru` file:\n\n```ruby\nrequire 'iodine'\nmodule WebsocketChat\n  def on_open client\n    # Pub/Sub directly to the client (or use a block to process the messages)\n    client.subscribe :chat\n    # Writing directly to the socket\n    client.write \"You're now in the chatroom.\"\n  end\n  def on_message client, data\n    # Strings and symbol channel names are equivalent.\n    client.publish \"chat\", data\n  end\n  extend self\nend\nAPP = Proc.new do |env|\n  if env['rack.upgrade?'.freeze] == :websocket\n    env['rack.upgrade'.freeze] = WebsocketChat\n    [0,{}, []] # It's possible to set cookies for the response.\n  elsif env['rack.upgrade?'.freeze] == :sse\n    puts \"SSE connections can only receive data from the server, the can't write.\"\n    env['rack.upgrade'.freeze] = WebsocketChat\n    [0,{}, []] # It's possible to set cookies for the response.\n  else\n    [200, {\"Content-Length\" =\u003e \"12\", \"Content-Type\" =\u003e \"text/plain\"}, [\"Welcome Home\"] ]\n  end\nend\n# Pus/Sub can be server oriented as well as connection bound\nIodine.subscribe(:chat) {|ch, msg| puts msg if Iodine.master? }\n# By default, Pub/Sub performs in process cluster mode.\nIodine.workers = 4\n# # in irb:\nIodine.listen service: :http, public: \"www/public\", handler: APP\nIodine.start\n# # or in config.ru\nrun APP\n```\n\n### Native Pub/Sub with *optional* Redis scaling\n\nIodine's core, `facil.io` offers a native Pub/Sub implementation that can be scaled across machine boundaries using Redis.\n\nThe default implementation covers the whole process cluster, so a single cluster doesn't need Redis\n\nOnce a single iodine process cluster isn't enough, horizontal scaling for the Pub/Sub layer is as simple as connecting iodine to Redis using the `-r \u003curl\u003e` from the command line. i.e.:\n\n```bash\n$ iodine -w -1 -t 8 -r redis://localhost\n```\n\nIt's also possible to initialize the iodine\u003c=\u003eRedis link using Ruby, directly from the application's code:\n\n```ruby\n# initialize the Redis engine for each iodine process.\nif ENV[\"REDIS_URL\"]\n  Iodine::PubSub.default = Iodine::PubSub::Redis.new(ENV[\"REDIS_URL\"])\nelse\n  puts \"* No Redis, it's okay, pub/sub will still run on the whole process cluster.\"\nend\n# ... the rest of the application remains unchanged.\n```\n\nIodine's Redis client can also be used for asynchronous Redis command execution. i.e.:\n\n```ruby\nif(Iodine::PubSub.default.is_a? Iodine::PubSub::Redis)\n  # Ask Redis about all it's client connections and print out the reply.\n  Iodine::PubSub.default.cmd(\"CLIENT LIST\") { |reply| puts reply }\nend\n```\n\n**Pub/Sub Details and Limitations:**\n\n* Iodine's Redis client does *not* support multiple databases. This is both because [database scoping is ignored by Redis during pub/sub](https://redis.io/topics/pubsub#database-amp-scoping) and because [Redis Cluster doesn't support multiple databases](https://redis.io/topics/cluster-spec). This indicated that multiple database support just isn't worth the extra effort and performance hit.\n\n* The iodine Redis client will use two Redis connections for the whole process cluster (a single publishing connection and a single subscription connection), minimizing the Redis load and network bandwidth.\n\n* Connections will be automatically re-established if timeouts or errors occur.\n\n### Hot Restart\n\nIodine will \"hot-restart\" the application by shutting down and re-spawning the worker processes.\n\nThis will clear away any memory fragmentation concerns and other issues that might plague a long running worker process or ruby application.\n\nTo hot-restart iodine, send the `SIGUSR1` signal to the root process.\n\nThe following code will hot-restart iodine every 4 hours when iodine is running in cluster mode:\n\n```ruby\nIodine.run_every(4 * 60 * 60 * 1000) do\n  Process.kill(\"SIGUSR1\", Process.pid) unless Iodine.worker?\nend\n```\n\nSince the master / root process doesn't handle any requests (it only handles pub/sub and house-keeping), it's memory map and process data shouldn't be as affected and the new worker processes should be healthier and more performant.\n\n**Note**: This will **not** re-load the application (any changes to the Ruby code require an actual restart).\n\n### Optimized HTTP logging\n\nBy default, iodine is pretty quiet. Some messages are logged to `stderr`, but not many.\n\nHowever, HTTP requests can be logged using iodine's optimized logger to `stderr`. Iodine will optimize the log output by caching the output time string which updates every second rather than every request.\n\nThis can be performed by setting the `-v` flag during startup, i.e.:\n\n```bash\nbundler exec iodine -p $PORT -t 16 -w 4 -v -www /my/public/folder\n```\n\nThe log output can be redirected to a file:\n\n```bash\nbundler exec iodine -p $PORT -v  2\u003emy_log.log\n```\n\nThe log output can also be redirected to a `stdout`:\n\n```bash\nbundler exec iodine -p $PORT -v  2\u003e\u00261\n```\n\n### Built-in support for Sequel and ActiveRecord\n\nIt's a well known fact that [Database connections require special attention when using `fork`-ing servers (multi-process servers)](https://devcenter.heroku.com/articles/concurrency-and-database-connections#multi-process-servers) such as Puma, Passenger (Pro) and iodine.\n\nHowever, it's also true that [these issues go unnoticed by many developers](https://stackoverflow.com/a/45570999/4025095), since application developers are (rightfully) focused on the application rather than the infrastructure.\n\nWith iodine, there's no need to worry.\n\nIodine provides built-in `fork` handling for both ActiveRecord and [Sequel](https://github.com/jeremyevans/sequel), in order to protect against these possible errors.\n\n### Client Support\n\nIodine supports raw (TCP/IP and Unix Sockets) client connections as well as WebSocket connections.\n\nThis can be utilized for communicating across micro services or taking advantage of persistent connection APIs such as ActionCable APIs, socket.io APIs etc'.\n\nHere is an example WebSocket client that will connect to the [WebSocket.org echo test service](https://www.websocket.org/echo.html) and send a number of pre-programmed messages.\n\n```ruby\nrequire 'iodine'\n\n# The client class\nclass EchoClient\n\n  def on_open(connection)\n    @messages = [ \"Hello World!\",\n      \"I'm alive and sending messages\",\n      \"I also receive messages\",\n      \"now that we all know this...\",\n      \"I can stop.\",\n      \"Goodbye.\" ]\n    send_one_message(connection)\n  end\n\n  def on_message(connection, message)\n    puts \"Received: #{message}\"\n    send_one_message(connection)\n  end\n\n  def on_close(connection)\n    # in this example, we stop iodine once the client is closed\n    puts \"* Client closed.\"\n    Iodine.stop\n  end\n\n  # We use this method to pop messages from the queue and send them\n  #\n  # When the queue is empty, we disconnect the client.\n  def send_one_message(connection)\n    msg = @messages.shift\n    if(msg)\n      connection.write msg\n    else\n      connection.close\n    end\n  end\nend\n\nIodine.threads = 1\nIodine.connect url: \"wss://echo.websocket.org\", handler: EchoClient.new, ping: 40\nIodine.start\n```\n\n### TLS \u003e= 1.2 support\n\n\u003e  Requires OpenSSL \u003e= `1.1.0`. On Heroku, requires `heroku-18`.\n\nIodine supports secure connections fore TLS version 1.2 **and up** (depending on the OpenSSL version).\n\nA self signed certificate is available using the `-tls` flag from the command-line.\n\nPEM encoded certificates (which is probably the most common format) can be loaded from the command-line (`-tls-cert` and `-tls-key`) or dynamically (using `Iodine::TLS`).\n\nThe TLS API is simplified but powerful, supporting the ALPN extension and peer verification (which client connections really should leverage).\n\nWhen enabling peer verification for server connections (using `Iodine::TLS#trust`), clients will be required to submit a trusted certificate in order to connect to the server.\n\n### TCP/IP (raw) sockets\n\nUpgrading to a custom protocol (i.e., in order to implement your own WebSocket protocol with special extensions) is available when neither WebSockets nor SSE connection upgrades were requested. In the following (terminal) example, we'll use an echo server without direct socket echo:\n\n```ruby\nrequire 'iodine'\nclass MyProtocol\n  def on_message client, data\n    # regular socket echo - NOT websockets\n    client.write data\n  end\nend\nAPP = Proc.new do |env|\n  if env[\"HTTP_UPGRADE\".freeze] =~ /echo/i.freeze\n    env['upgrade.tcp'.freeze] = MyProtocol.new\n    # an HTTP response will be sent before changing protocols.\n    [101, { \"Upgrade\" =\u003e \"echo\" }, []]\n  else\n    [200, {\"Content-Length\" =\u003e \"12\", \"Content-Type\" =\u003e \"text/plain\"}, [\"Welcome Home\"] ]\n  end\nend\n# # in irb:\nIodine.listen service: :http, public: \"www/public\", handler: APP\nIodine.threads = 1\nIodine.start\n# # or in config.ru\nrun APP\n```\n\n### How does it compare to other servers?\n\nIn my tests, pitching Iodine against Puma, Iodine was anywhere between x1.5 and more than x10 faster than Puma (depending on use-case and settings).\n\nSuch a big difference is suspect and I recommend that you test it yourself - even better if you test performance using your own application and a number of possible different settings (how many threads per CPU core? how many worker processes? middleware vs. server request logging, etc').\n\nI recommend benchmarking the performance for yourself using `wrk` or `ab`:\n\n```bash\n$ wrk -c200 -d4 -t2 http://localhost:3000/\n# or\n$ ab -n 100000 -c 200 -k http://127.0.0.1:3000/\n```\n\nThe best application to use for benchmarking is your actual application. Or, you could create a simple `config.ru` file with a __hello world__ app:\n\n```ruby\nApp = Proc.new do |env|\n   [200,\n     {   \"Content-Type\" =\u003e \"text/html\".freeze,\n         \"Content-Length\" =\u003e \"16\".freeze },\n     ['Hello from Rack!'.freeze]  ]\nend\n\nrun App\n```\n\nThen start comparing servers. Here are the settings I used to compare iodine and Puma (4 processes, 4 threads):\n\n```bash\n$ RACK_ENV=production iodine -p 3000 -t 4 -w 4\n# vs.\n$ RACK_ENV=production puma -p 3000 -t 4 -w 4\n# Review the `iodine -?` help for more command line options.\n```\n\nIt's recommended that the servers (Iodine/Puma) and the client (`wrk`/`ab`) run on separate machines.\n\nIt is worth noting that iodine can also speed up logging by replacing the logging middleware with `iodine -v`. This approach uses less memory and improves performance at the expense of fuzzy timing and some string caching.\n\nOn my machine, testing with the logging functionality enabled, iodine was more then 10 times faster than puma (60.9K req/sec vs. 5.3K req/sec)\n\n### A few notes\n\nIodine's upgrade / callback design has a number of benefits, some of them related to better IO handling, resource optimization (no need for two IO polling systems), etc. This also allows us to use middleware without interfering with connection upgrades and provides backwards compatibility.\n\nIodine's HTTP server imposes a few restrictions for performance and security reasons, such as limiting each header line to 8Kb. These restrictions shouldn't be an issue and are similar to limitations imposed by Apache or Nginx.\n\nIf you still want to use Rack's `hijack` API, iodine will support you - but be aware that you will need to implement your own reactor and thread pool for any sockets you hijack, as well as a socket buffer for non-blocking `write` operations (why do that when you can write a protocol object and have the main reactor manage the socket?).\n\n## Installation\n\nTo install iodine, simply install the the `iodine` gem:\n\n```bash\n$ gem install iodine\n```\n\nIodine is written in C and allows some compile-time customizations, such as:\n\n* `FIO_FORCE_MALLOC` - avoids iodine's custom memory allocator and use `malloc` instead (mostly used when debugging iodine or when using a different memory allocator).\n\n* `FIO_MAX_SOCK_CAPACITY` - limits iodine's maximum client capacity. Defaults to 131,072 clients.\n\n* `FIO_USE_RISKY_HASH` - replaces SipHash with RiskyHash for iodine's internal hash maps.\n\n    Since iodine hash maps have internal protection against collisions and hash flooding attacks, it's possible for iodine to leverage RiskyHash, which is faster than SipHash.\n\n    By default, SipHash will be used. This is a community related choice, since the community seems to believe a hash function should protect the hash map rather than it being enough for a hash map implementation to be attack resistance.\n\n* `HTTP_MAX_HEADER_COUNT` - limits the number of headers the HTTP server will accept before disconnecting a client (security). Defaults to 128 headers (permissive).\n\n* `HTTP_MAX_HEADER_LENGTH` - limits the number of bytes allowed for a single header (pre-allocated memory per connection + security). Defaults to 8Kb per header line (normal).\n\n* `HTTP_BUSY_UNLESS_HAS_FDS` - requires at least X number of free file descriptors (for new database connections, etc') before accepting a new HTTP client.\n\n* `FIO_ENGINE_POLL` - prefer the `poll` system call over `epoll` or `kqueue` (not recommended).\n\n* `FIO_LOG_LENGTH_LIMIT` - sets the limit on iodine's logging messages (uses stack memory, so limits must be reasonable. Defaults to 2048.\n\n* `FIO_TLS_PRINT_SECRET` - if true, the OpenSSL master key will be printed as debug message level log. Use only for testing (with WireShark etc'), never in production! Default: false.\n\nThese options can be used, for example, like so:\n\n```bash\n  gem install iodine -- \\\n      --with-cflags=\\\"-DHTTP_MAX_HEADER_LENGTH=48000 -DFIO_FORCE_MALLOC=1 -DHTTP_MAX_HEADER_COUNT=64\\\"\n```\n\nMore possible compile time options can be found in the [facil.io documentation](http://facil.io).\n\n## Evented oriented design with extra safety\n\nIodine is an evented server, similar in its architecture to `nginx` and `puma`. It's different than the simple \"thread-per-client\" design that is often taught when we begin to learn about network programming.\n\nBy leveraging `epoll` (on Linux) and `kqueue` (on BSD), iodine can listen to multiple network events on multiple sockets using a single thread.\n\nAll these events go into a task queue, together with the application events and any user generated tasks, such as ones scheduled by [`Iodine.run`](http://www.rubydoc.info/github/boazsegev/iodine/Iodine#run-class_method).\n\nIn pseudo-code, this might look like this\n\n```ruby\nQUEUE = Queue.new\n\ndef server_cycle\n    if(QUEUE.empty?)\n      QUEUE \u003c\u003c get_next_32_socket_events # these events schedule the proper user code to run\n    end\n    QUEUE \u003c\u003c server_cycle\nend\n\ndef run_server\n      while ((event = QUEUE.pop))\n            event.shift.call(*event)\n      end\nend\n```\n\nIn pure Ruby (without using C extensions or Java), it's possible to do the same by using `select`... and although `select` has some issues, it could work well for lighter loads.\n\nThe server events are fairly fast and fragmented (longer code is fragmented across multiple events), so one thread is enough to run the server including it's static file service and everything...\n\n...but single threaded mode should probably be avoided.\n\n\nIt's very common that the application's code will run slower and require external resources (i.e., databases, a custom pub/sub service, etc'). This slow code could \"starve\" the server, which is patiently waiting to run it's short tasks on the same thread.\n\nThe thread pool is there to help slow user code.\n\nThe slower your application code, the more threads you will need to keep the server running in a responsive manner (note that responsiveness and speed aren't always the same).\n\nTo make a thread pool easier and safer to use, iodine makes sure that no connection task / callback is called concurrently for the same connection.\n\nFor example, a is a WebSocket connection is already busy in it's `on_message` callback, no other messages will be forwarded to the callback until the current callback returns.\n\n## Free, as in freedom (BYO beer)\n\nIodine is **free** and **open source**, so why not take it out for a spin?\n\nIt's installable just like any other gem on Ruby MRI, run:\n\n```\n$ gem install iodine\n```\n\nIf building the native C extension fails, please note that some Ruby installations, such as on Ubuntu, require that you separately install the development headers (`ruby.h` and friends). I have no idea why they do that, as you will need the development headers for any native gems you want to install - so hurry up and get them.\n\nIf you have the development headers but still can't compile the iodine extension, [open an issue](https://github.com/boazsegev/iodine/issues) with any messages you're getting and I'll be happy to look into it.\n\n## Mr. Sandman, write me a server\n\nIodine allows custom TCP/IP server authoring, for those cases where we need raw TCP/IP (UDP isn't supported just yet).\n\nHere's a short and sweet echo server - No HTTP, just use `telnet`:\n\n```ruby\nUSE_TLS = false\n\nrequire 'iodine'\n\n# an echo protocol with asynchronous notifications.\nclass EchoProtocol\n  # `on_message` is called when data is available.\n  def on_message client, buffer\n    # writing will never block and will use a buffer written in C when needed.\n    client.write buffer\n    # close will be performed only once all the data in the write buffer\n    # was sent. use `force_close` to close early.\n    client.close if buffer =~ /^bye[\\r\\n]/i\n    # run asynchronous tasks... after a set number of milliseconds\n    Iodine.run_after(1000) do\n      # or schedule the task immediately\n      Iodine.run do\n        puts \"Echoed data: #{buffer}\"\n      end\n    end\n  end\nend\n\ntls = USE_TLS ? Iodine::TLS.new(\"localhost\") : nil\n\n# listen on port 3000 for the echo protocol.\nIodine.listen(port: \"3000\", tls: tls) { EchoProtocol.new }\nIodine.threads = 1\nIodine.workers = 1\nIodine.start\n```\n\nOr a nice plain text chat room (connect using `telnet` or `nc` ):\n\n```ruby\nrequire 'iodine'\n\n# a chat protocol with asynchronous notifications.\nclass ChatProtocol\n  def initialize nickname = \"guest\"\n    @nickname = nickname\n  end\n  def on_open client\n    client.subscribe :chat\n    client.publish :chat, \"#{@nickname} joined chat.\\n\"\n    client.timeout = 40\n  end\n  def on_close client\n    client.publish :chat, \"#{@nickname} left chat.\\n\"\n  end\n  def on_shutdown client\n    client.write \"Server is shutting down... try reconnecting later.\\n\"\n  end\n  def on_message client, buffer\n    if(buffer[-1] == \"\\n\")\n      client.publish :chat, \"#{@nickname}: #{buffer}\"\n    else\n      client.publish :chat, \"#{@nickname}: #{buffer}\\n\"\n    end\n    # close will be performed only once all the data in the outgoing buffer\n    client.close if buffer =~ /^bye[\\r\\n]/i\n  end\n  def ping client\n    client.write \"(ping) Are you there, #{@nickname}...?\\n\"\n  end\nend\n\n# an initial login protocol\nclass LoginProtocol\n  def on_open client\n    client.write \"Enter nickname to log in to chat room:\\n\"\n    client.timeout = 10\n  end\n  def ping client\n    client.write \"Time's up... goodbye.\\n\"\n    client.close\n  end\n  def on_message client, buffer\n    # validate nickname and switch connection callback to ChatProtocol\n    nickname = buffer.split(\"\\n\")[0]\n    while (nickname \u0026\u0026 nickname.length() \u003e 0 \u0026\u0026 (nickname[-1] == '\\n' || nickname[-1] == '\\r'))\n      nickname = nickname.slice(0, nickname.length() -1)\n    end\n    if(nickname \u0026\u0026 nickname.length() \u003e 0 \u0026\u0026 buffer.split(\"\\n\").length() == 1)\n      chat = ChatProtocol.new(nickname)\n      client.handler = chat\n    else\n      client.write \"Nickname error, try again.\\n\"\n      on_open client\n    end\n  end\nend\n\n# listen on port 3000\nIodine.listen(port: 3000) { LoginProtocol.new }\nIodine.threads = 1\nIodine.workers = 1\nIodine.start\n```\n\n### Why not EventMachine?\n\nEventMachine attempts to give the developer access to the network layer while Iodine attempts to abstract the network layer away and offer the developer a distraction free platform.\n\nYou can go ahead and use EventMachine if you like. They're doing amazing work on that one and it's been used a lot in Ruby-land... really, tons of good developers and people on that project.\n\nBut why not take iodine out for a spin and see for yourself?\n\n## Can I contribute?\n\nYes, please, here are some thoughts:\n\n* I'm really not good at writing automated tests and benchmarks, any help would be appreciated. I keep testing manually and that's less then ideal (and it's mistake prone).\n\n* PRs or issues related to [the `facil.io` C framework](https://github.com/boazsegev/facil.io) should be placed in [the `facil.io` repository](https://github.com/boazsegev/facil.io).\n\n* Bug reports and pull requests are welcome on GitHub at https://github.com/boazsegev/iodine.\n\n* If we can write a Java wrapper for [the `facil.io` C framework](https://github.com/boazsegev/facil.io), it would be nice... but it could be as big a project as the whole gem, as a lot of minor details are implemented within the bridge between these two languages.\n\n* If you love the project or thought the code was nice, maybe helped you in your own project, drop me a line. I'd love to know.\n\n### Running the Tests\n\nRunning this task will compile the C extensions then run RSpec tests:\n\n```sh\nbundle exec rake spec\n```\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fboazsegev%2Fiodine","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fboazsegev%2Fiodine","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fboazsegev%2Fiodine/lists"}