Skip to main content

eio

Eio concurrency patterns for OCaml applications. Use when Claude needs to: (1) Write concurrent OCaml code with Eio, (2) Handle network operations with cohttp-eio, (3) Manage resource lifecycles with switches, (4) Implement rate limiting or synchronization, (5) Create parallel operations with fibers, (6) Test async code with Eio_mock, (7) Integrate with bytesrw for streaming, or any other Eio-based concurrency tasks

v1.0.0New

Unsigned, install at your own risk

Unverified

This skill has no cryptographic signature attached. We can't verify the contents match what the publisher intended.

Install this skill

No account required. Pick your tool, or use the command that detects it for you.

Run in your terminal. It detects your AI tool.

npx @skills-hub-ai/cli install ocaml-dev-eio
Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/ocaml-dev-eio/SKILL.md

Setup guide →
0Save

Instructions

Eio Concurrency

Core Concepts

Why Eio

Eio is an effects-based IO library for OCaml 5. Advantages over Lwt/Async:

  • Direct-style code: No monads, concurrent code looks like sequential code
  • Performance: Real stacks, no heap allocations to simulate continuations
  • Better backtraces: Exceptions show proper call traces
  • Platform optimization: Generic API with optimized backends (Linux io_uring, POSIX, Windows)

Capability-Based Design

Pass capabilities explicitly instead of using global resources:

type t = {
  net : _ Eio.Net.t;
  clock : _ Eio.Time.clock;
  fs : _ Eio.Path.t;
}

(* Function signature reveals what resources it needs *)
val connect : net:_ Eio.Net.t -> host:string -> connection

Do: Pass net, clock, fs explicitly—makes dependencies clear and testable.

Don't: Use global modules like Unix.gettimeofday or access ambient resources.

Structured Concurrency with Switches

Eio.Switch.run manages resource and fiber lifecycles:

Eio.Switch.run @@ fun sw ->
  let conn = connect ~sw server in
  (* conn automatically closed when sw exits *)
  process conn

Do: Create switches in the smallest possible scope.

Don't: Take a switch argument if you could create one internally.

Fibers

Lightweight concurrent units running on a single core:

(* Run two operations concurrently *)
Eio.Fiber.both
  (fun () -> download file1)
  (fun () -> download file2)

(* Only one fiber executes at a time until one performs an effect *)

Cancellation

Cancellation contexts form a tree. Uncaught exceptions propagate upward, cancelling siblings:

(* If one branch fails, the other gets Cancelled *)
Eio.Fiber.both
  (fun () -> may_fail ())
  (fun () -> other_work ())  (* receives Cancelled if may_fail raises *)

Use Cancel.protect for operations that must complete:

Eio.Cancel.protect @@ fun () ->
  (* This won't be cancelled even if parent is *)
  flush_and_close connection

Common Patterns

Concurrent Operations

(* Parallel map *)
let fetch_all_items api item_ids =
  Eio.Fiber.List.map (fun id -> Api.item_info api id) item_ids

(* Race with timeout *)
let with_timeout ~clock duration fn =
  Eio.Fiber.first
    (fun () -> Eio.Time.sleep clock duration; Error `Timeout)
    (fun () -> Ok (fn ()))

(* Fork background task attached to switch *)
Eio.Fiber.fork ~sw (fun () -> background_work ())

File Operations

let ( / ) = Eio.Path.( / )

(* Read file *)
let content = Eio.Path.load (fs / "config.json")

(* Write file with permissions *)
Eio.Path.save ~create:(`Or_truncate 0o600) (fs / "data.bin") content

(* Create directory if needed *)
Eio.Path.mkdirs ~exists_ok:true ~perm:0o755 (fs / "cache")

(* Clean up directory tree *)
Eio.Path.rmtree (fs / "tmp")

(* Check file type *)
match Eio.Path.kind ~follow:true path with
| `Directory -> ...
| `Regular_file -> ...
| `Not_found -> ...

Network Operations

(* TCP client *)
Eio.Net.connect ~sw net (`Tcp (addr, port))

(* TCP server *)
Eio.Net.run_server sock ~on_error:log_error
  ~max_connections:100
  (fun ~sw flow addr -> handle_client ~sw flow)

HTTPS with cohttp-eio

let https_handler uri raw_flow =
  let tls_config = create_tls_config () in
  let host = Uri.host uri |> Option.map Domain_name.(host_exn % of_string_exn) in
  Tls_eio.client_of_flow ?host tls_config raw_flow

let client = Cohttp_eio.Client.make net ~https:(Some https_handler)

Buffered Reading

Always use max_size to prevent memory exhaustion:

let body = Eio.Buf_read.(of_flow ~max_size:10_000_000 flow |> take_all)

Synchronization Primitives

Mutex:

let mutex = Eio.Mutex.create ()
Eio.Mutex.use_rw mutex (fun () -> shared_state := new_value)

Semaphore for rate limiting:

let limiter = Eio.Semaphore.make 10
let with_rate_limit fn =
  Eio.Semaphore.acquire limiter;
  Fun.protect ~finally:(fun () -> Eio.Semaphore.release limiter) fn

Stream for producer/consumer:

let queue = Eio.Stream.create 100
Eio.Stream.add queue item      (* producer *)
let item = Eio.Stream.take queue  (* consumer, blocks if empty *)

Condition variables (must check in loop):

let cond = Eio.Condition.create ()
let mutex = Eio.Mutex.create ()

(* Waiter - MUST use while loop *)
Eio.Mutex.use_rw ~protect:false mutex (fun () ->
  while not (check_condition ()) do
    Eio.Condition.await cond mutex
  done)

(* Signaler *)
Eio.Condition.broadcast cond

Integration with bytesrw

Bridge Eio flows to bytesrw for streaming binary parsing:

(* Eio flow → bytesrw reader *)
let reader_of_flow ?(buf_len = 4096) flow =
  let cs = Cstruct.create buf_len in
  let read () =
    match Eio.Flow.single_read flow cs with
    | 0 -> Bytesrw.Bytes.Slice.eod
    | n ->
        let buf = Cstruct.to_bytes (Cstruct.sub cs 0 n) in
        Bytesrw.Bytes.Slice.make buf ~first:0 ~length:n
    | exception End_of_file -> Bytesrw.Bytes.Slice.eod
  in
  Bytesrw.Bytes.Reader.make read

(* Then use with Binary.Reader *)
let r = Binary.Reader.of_reader (reader_of_flow flow)
let frame = Tc_frame.parse r  (* effects propagate through *)

Note: This involves a copy from Cstruct (Bigarray) to bytes (heap). Unavoidable until OCaml has non-moving bytes.

RNG Initialization

Critical for crypto: Initialize RNG before any crypto operations.

(* For Eio applications *)
Eio_main.run @@ fun env ->
  Mirage_crypto_rng_eio.run (module Mirage_crypto_rng.Fortuna) env @@ fun () ->
    (* RNG now available *)
    let iv = Mirage_crypto_rng.generate 12 in
    ...

(* For Unix applications (simpler but less integrated) *)
Mirage_crypto_rng_unix.initialize (module Mirage_crypto_rng.Fortuna)

Failure to initialize results in predictable random numbers, breaking crypto security.

Error Handling

Errors use Eio.Io (err, context) with nested error codes:

try
  Eio.Net.connect ~sw net addr
with
| Eio.Io (Eio.Net.E (Connection_failure _), _) ->
    (* Specific error *)
    Error `Connection_failed
| Eio.Io (Eio.Net.E _, _) ->
    (* Any network error *)
    Error `Network_error
| Eio.Io _ ->
    (* Any Eio error *)
    Error `Io_error

Add context when re-raising:

Eio.Exn.reraise_with_context exn "while connecting to %s" host

For tests, hide backend details:

Eio.Exn.Backend.show := false

Testing with Eio_mock

Library: eio.mock (not eio_mock)

Test Setup Pattern

let setup_test f () =
  Mirage_crypto_rng_unix.use_default ();  (* or initialize RNG *)
  Eio_main.run @@ fun env ->
  Eio.Switch.run @@ fun sw ->
  let fs = Eio.Stdenv.fs env in
  let tmp = Eio.Path.(fs / Filename.get_temp_dir_name () / "test-dir") in
  (try Eio.Path.rmtree tmp with _ -> ());
  Eio.Path.mkdirs ~exists_ok:true ~perm:0o755 tmp;
  Fun.protect
    ~finally:(fun () -> try Eio.Path.rmtree tmp with _ -> ())
    (fun () -> f ~sw tmp)

let test_something = setup_test @@ fun ~sw tmp ->
  (* test code here *)

Mock Flow

let test_api_call () =
  Eio_main.run @@ fun _env ->
  let flow = Eio_mock.Flow.make "response" in
  (* IMPORTANT: Always end with `Raise End_of_file *)
  Eio_mock.Flow.on_read flow [
    `Return "{\"ok\": true}";
    `Raise End_of_file;
  ];
  (* use flow *)

Simulating Chunked Data

let test_partial_reads () =
  Eio_main.run @@ fun _env ->
  let flow = Eio_mock.Flow.make "chunked" in
  Eio_mock.Flow.on_read flow [
    `Return "\x00\x01";      (* First 2 bytes *)
    `Return "\x02\x03";      (* Next 2 bytes *)
    `Raise End_of_file;
  ];
  (* Parser must handle values spanning chunks *)

Mock Network

let test_network () =
  Eio_main.run @@ fun _env ->
  let net = Eio_mock.Net.make "mocknet" in
  let flow = Eio_mock.Flow.make "conn" in
  Eio_mock.Net.on_connect net [`Return flow];
  Eio_mock.Flow.on_read flow [`Return "data"; `Raise End_of_file];
  (* test network operations *)

Deadlock Detection

Eio_mock.Backend.run automatically detects deadlocks in tests.

Good and Bad Examples

Capability Passing

Bad: Using global/ambient resources

let fetch_data url =
  let now = Unix.gettimeofday () in  (* Global! *)
  let body = Http.get url in         (* Where does network come from? *)
  { timestamp = now; data = body }

Good: Explicit capability parameters

let fetch_data ~net ~clock url =
  let now = Eio.Time.now clock in
  Eio.Switch.run @@ fun sw ->
  let body = Http.get ~sw net url in
  { timestamp = now; data = body }

Switch Scope

Bad: Taking switch as argument when not needed

(* Why does this need a switch? Caller must manage lifetime *)
let read_config ~sw ~fs path =
  Eio.Path.load (fs / path)  (* No resources to manage! *)

Good: Create switch internally when needed

(* No switch needed - just reads a file *)
let read_config ~fs path =
  Eio.Path.load (fs / path)

(* Switch needed - manages connection lifetime *)
let with_connection ~sw ~net addr f =
  let conn = Eio.Net.connect ~sw net addr in
  f conn  (* conn closed when sw exits *)

Buffered Reading

Bad: No size limit allows memory exhaustion

let read_body flow =
  Eio.Buf_read.(of_flow flow |> take_all)  (* Unbounded! *)

Good: Always specify max_size

let read_body flow =
  Eio.Buf_read.(of_flow ~max_size:10_000_000 flow |> take_all)

Condition Variables

Bad: Single check can miss wakeups

Eio.Mutex.use_rw ~protect:false mutex (fun () ->
  if not (check_condition ()) then  (* Single if! *)
    Eio.Condition.await cond mutex;
  do_work ())

Good: Loop until condition is true

Eio.Mutex.use_rw ~protect:false mutex (fun () ->
  while not (check_condition ()) do  (* Loop handles spurious wakeups *)
    Eio.Condition.await cond mutex
  done;
  do_work ())

Error Handling

Bad: Catching all Eio errors indiscriminately

let connect addr =
  try Eio.Net.connect ~sw net addr
  with Eio.Io _ -> failwith "connection failed"  (* Loses context! *)

Good: Match specific errors, preserve context

let connect addr =
  try Eio.Net.connect ~sw net addr
  with
  | Eio.Io (Eio.Net.E (Connection_failure reason), _) ->
      Error (`Connection_failed reason)
  | Eio.Io (Eio.Net.E Connection_refused, _) ->
      Error `Refused
  | Eio.Io _ as exn ->
      Eio.Exn.reraise_with_context exn "connecting to %s" addr

Mock Testing

Bad: Mock flow without End_of_file hangs forever

let test_read () =
  Eio_main.run @@ fun _env ->
  let flow = Eio_mock.Flow.make "test" in
  Eio_mock.Flow.on_read flow [
    `Return "data";
    (* Missing End_of_file! Test hangs *)
  ];
  read_all flow

Good: Always end mock reads with End_of_file

let test_read () =
  Eio_main.run @@ fun _env ->
  let flow = Eio_mock.Flow.make "test" in
  Eio_mock.Flow.on_read flow [
    `Return "data";
    `Raise End_of_file;  (* Required! *)
  ];
  read_all flow

Cancellation Safety

Bad: Critical cleanup can be cancelled

Eio.Fiber.both
  (fun () -> may_fail ())
  (fun () ->
    do_work ();
    flush_and_close connection)  (* May be cancelled mid-flush! *)

Good: Protect critical operations

Eio.Fiber.both
  (fun () -> may_fail ())
  (fun () ->
    do_work ();
    Eio.Cancel.protect @@ fun () ->
    flush_and_close connection)  (* Completes even if cancelled *)

Common Gotchas

IssueProblemSolution
Racing readsBoth reads may complete at kernel levelDon't rely on Fiber.first for mutual exclusion
Signal handlersMost operations risk deadlockOnly Eio.Condition.broadcast is safe
Condition spurious wakeupMay wake without signalAlways check condition in while loop
Mutex in signal handlerRe-entrancy issuesUse conditions instead
Forgetting End_of_fileMock flow hangsAlways end mock reads with Raise End_of_file
Missing RNG initPredictable cryptoInitialize before any crypto operations

Library Integration

LibraryPurposeNotes
Lwt_eioRun Lwt + Eio togetherGradual migration path
Async_eioRun Async + Eio togetherExperimental
bytesrwStreaming byte parsingRequires copy (Cstruct→bytes)
cohttp-eioHTTP client/serverNative Eio support
tls-eioTLS connectionsUse with cohttp-eio for HTTPS
mirage-crypto-rngCrypto RNGUse .unix sublibrary for entropy

Best Practices

PracticeDescription
Capability passingPass net, clock, fs explicitly
Structured concurrencyUse Switch.run, keep scopes small
Handle errors at boundariesConvert Eio.Io to domain errors
Buffered readingUse Buf_read with max_size
Parallel with fibersFiber.List.map, Fiber.both, Fiber.first
Isolate blockingEio_unix.run_in_systhread for non-Eio blocking
Test with mocksEio_mock for deterministic tests
Initialize RNGBefore any crypto operations

References

  • Eio repository: https://github.com/ocaml-multicore/eio
  • Eio documentation: https://ocaml.org/p/eio/latest/doc/
  • cohttp-eio: https://github.com/mirage/ocaml-cohttp
  • bytesrw: https://erratique.ch/software/bytesrw
This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

Browse all →
testingTesting strategies for OCaml libraries. Use when discussing tests, alcotest, eio mocks, test structure, or test-driven development in OCaml projects.0 installssecuritySecurity hardening for OCaml libraries through systematic vulnerability research. Use when Claude needs to: (1) Research CVEs in similar implementations (C, Rust, Go, Python) and add regression tests, (2) Add fuzz tests for parsers and encoders, (3) Audit integer handling and buffer operations, (4) Test boundary conditions and malformed input, (5) Review cryptographic usage, (6) Add defensive checks against common vulnerability classes0 installsjsontJSON type-safe encoding and decoding using the OCaml jsont library. Use when Claude needs to: define typed JSON codecs for OCaml record types, parse JSON strings to OCaml values, or serialize OCaml values to JSON, or work with nested JSON structures0 installsnpm-publishingPublishing OCaml to npm via js_of_ocaml and wasm_of_ocaml. Use when discussing browser targets, JavaScript compilation, WASM output, npm packages, or the two-branch workflow.0 installsreview-ocamlTwo-phase review of an OCaml project. Use when the user asks to review an OCaml codebase, audit its module interfaces, restructure or redocument .mli files, or hunt for redundancy, dead code and optimisation opportunities across implementations. Phase one reads only dune and .mli files to judge the public interfaces; phase two dispatches a subagent per module to review the implementation.0 installsresultOCaml Result type patterns using OCaml 5.x stdlib. Use when Claude needs to: (1) Handle errors with Result types, (2) Chain Result operations with let*, (3) Extract values from Ok/Error, (4) Refactor code using local let* bindings to use Result.Syntax0 installs

More from OCaml Dev (avsm)

View source →
doc-styleOCaml comment and ocamldoc writing style, in the voice of a POSIX manual page. Use whenever writing, rewording, reviewing or deleting any OCaml comment or documentation. Triggers on ocamldoc, odoc, doc comments, (** ... *), .mli documentation, .mld pages, documenting a function, type or module, and on any request to add, tidy, rewrite or strip OCaml comments.0 installsdune-migrationMigrating OCaml projects from ocamlbuild/topkg to dune. Use when discussing _tags files, .mllib files, pkg/pkg.ml, topkg, or build system migration.0 installseffectsOCaml 5 algebraic effects design patterns. Use when Claude needs to: (1) Design APIs that interact with effect-based schedulers, (2) Decide between effects vs exceptions, (3) Integrate libraries with Eio or affect, (4) Handle suspension vs error cases in streaming code, (5) Understand the layered effect design principle0 installsfuzzOCaml fuzz testing with Crowbar for protocol implementations. Use when Claude needs to: (1) Write fuzz tests for parsers and encoders, (2) Test roundtrip invariants (parse(encode(x)) = x), (3) Verify boundary conditions and error handling, (4) Test state machines and transitions, (5) Organize fuzz test suites for large codebases, (6) Run long-lived AFL campaigns with Crowbar0 installslogsOCaml Logs library patterns for structured logging. Use when Claude needs to: (1) Add logging to OCaml modules, (2) Create per-module log sources, (3) Use appropriate log levels, (4) Add structured tags to log messages0 installscode-styleOCaml coding style and refactoring patterns. Use when the user asks to tidy, clean up, refactor, or improve OCaml code, reviewing code quality, enforcing naming conventions, or reducing complexity.0 installs

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.635 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.535 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.346 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.246 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.173 installsusing-superpowersUse when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions145 installs

Frequently asked questions about eio

What does the eio skill do?

Eio concurrency patterns for OCaml applications. Use when Claude needs to: (1) Write concurrent OCaml code with Eio, (2) Handle network operations with cohttp-eio, (3) Manage resource lifecycles with switches, (4) Implement rate limiting or synchronization, (5) Create parallel operations with fibers, (6) Test async code with Eio_mock, (7) Integrate with bytesrw for streaming, or any other Eio-based concurrency tasks It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the eio skill?

Run `npx @skills-hub-ai/cli install ocaml-dev-eio` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/ocaml-dev-eio/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does eio work with?

eio runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the eio skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use eio after installing it?

In Claude Code, type `/ocaml-dev-eio` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the eio skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.