OCaml HTTP Clients in 2026: cohttp vs ezcurl vs piaf vs ocurl

OCaml does not have one HTTP client. It has four, and the one you pick silently decides your concurrency model, your TLS stack, and how much of your build depends on a C library. Choose wrong and you will spend a week threading Lwt through a codebase that wanted Eio, or shipping a statically linked binary that suddenly needs libcurl.so on the target machine.

This is not a “which library has more stars” question. It is a question about effect systems. cohttp v6.3.0 (785 stars, last push 2026-12-03) is a portable parser with five backends. piaf 0.2.0 (219 stars) is written against Eio and speaks HTTP/2 natively. ezcurl 0.4 (31 stars) is a thin, stable wrapper over libcurl. ocurl 0.10.1 (63 stars, pushed 2026-12-02) is the raw binding that ezcurl sits on top of. Picking the wrong layer costs you more than picking the wrong brand.

The 30-Second Verdict

Use cohttp if you are already on Lwt or Async — it is the only one with a battle-tested server and client, and the parser is reusable across targets. Use piaf if your project is Eio-native and you need HTTP/2 without a C dependency. Use ezcurl if you want libcurl’s proxy handling, redirects, and TLS behaviour with a ten-line API and no monad gymnastics. Use ocurl only if you need a libcurl feature ezcurl does not expose — otherwise you are writing boilerplate for no gain.

If you are starting a new OCaml service today and have no legacy constraint: piaf for outbound calls inside an Eio application, cohttp for anything that must also serve traffic on an Lwt stack. Do not mix two effect systems in one binary just to get an HTTP/2 client.

How the Four Compare

cohttpezcurlpiafocurl
Latest version6.3.00.40.2.00.10.1
Stars7853121963
Last push2026-12-032026-06-222026-07-252026-12-02
ConcurrencyLwt / Async / Eio (separate packages)Blocking, plus ezcurl-lwtEioBlocking
HTTP/2No (HTTP/1.1)Via libcurlNative HTTP/1.x + HTTP/2Via libcurl
TLS backendocaml-tls or ocaml-ssl (conduit)libcurl’s TLSocaml-tlslibcurl’s TLS
C dependencyNone (pure OCaml)libcurlNonelibcurl
Server includedYesNoNoNo
API surfaceLarge (client, server, headers, body)Tiny (get/post)Medium (Client.Oneshot)Large (handles, options)
LicenceISCMITBSD-3MIT

Two rows in that table decide almost every real deployment. HTTP/2 matters if you call a modern CDN or gRPC-gateway endpoint that refuses HTTP/1.1; only piaf and the libcurl-backed pair give it to you. Pure OCaml matters if you build MirageOS unikernels or ship static binaries; that rules out ezcurl and ocurl immediately.

Decision Matrix: Pick By Use Case

Use caseRecommendedWhy
Existing Lwt service calling a REST APIcohttp-lwt-unixSame event loop, no FFI, mature timeout handling
Eio app, needs HTTP/2 or many parallel requestspiafNative Eio integration, Oneshot API, no C deps
Shell script or CLI that fetches a URLezcurlEzcurl.get ~url () and you are done
Static/musl binary for a minimal containercohttp or piafNo libcurl.so in the image
Corporate proxy, NTLM, or exotic TLS settingsezcurl / ocurllibcurl has already solved it
Serving HTTP and calling downstream APIscohttpOnly option with a server in the same package family
Fine-grained control of a libcurl handleocurlDirect Curl.t access, reuse across calls

cohttp — The Default, and Why It Is Really Five Libraries

cohttp’s own README is explicit that the package is a portable HTTP parser plus backends: Cohttp_lwt_unix, Cohttp_async, Cohttp_lwt_jsoo, Cohttp_curl (which wraps ocurl), Cohttp_eio. This is the reason it survives: your request-building code does not change when your effect system does. The cost is that “cohttp” is not one dependency — it is one per backend, and installing the wrong combination is a classic first-day error.

The canonical client from the repo README:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
open Lwt
open Cohttp
open Cohttp_lwt_unix

let main =
  Client.get (Uri.of_string "https://www.reddit.com/") >>= fun (resp, body) ->
  let code = resp |> Response.status |> Code.code_of_status in
  Printf.printf "Response code: %d\n" code;
  Printf.printf "Headers: %s\n" (resp |> Response.headers |> Header.to_string);
  body |> Cohttp_lwt.Body.to_string >|= fun body ->
  Printf.printf "Body of length: %d\n" (String.length body);
  body

let () =
  let body = Lwt_main.run main in
  print_endline ("Received body\n" ^ body)

The dune stanza from the same README is deliberately minimal — one library name, and the backend comes with it:

1
2
3
4
(executable
 (public_name client_example)
 (name client_example)
 (libraries cohttp-lwt-unix))

Installation splits by backend, and you must install the TLS companion yourself:

1
2
3
4
opam install cohttp-lwt-unix cohttp-async
# HTTPS for the Lwt backend: pick one
opam install tls-lwt      # ocaml-tls
opam install lwt_ssl      # ocaml-ssl (default when both present)

That last detail is a real trap. cohttp’s README states that when both TLS stacks are installed, ocaml-ssl is chosen, and you force the pure-OCaml path with CONDUIT_TLS=native. In a container where you added lwt_ssl “just in case”, you are silently running OpenSSL through FFI and reintroducing the C dependency you thought you avoided.

ezcurl — libcurl With an OCaml Face

ezcurl’s stated goals are the most honest in this comparison: “be as simple to use as possible”, “be as reliable as possible (work is done by cURL and the ocurl bindings anyway)”, “stable API with few dependencies, so that user code compiles without breakage for a long time”. Its opam file confirms the shape — version 0.4, depending on curl >= 0.8, dune >= 3.0, OCaml >= 4.11, and nothing else at runtime.

From the README, the entire synchronous API in three lines:

1
2
3
4
5
6
# #require "ezcurl";;
# let url = "https://curl.haxx.se/";;
# let res = Ezcurl.get ~url ();;
# let content = match res with Ok c -> c | Error (_,s) -> failwith s;;
# content.Ezcurl.code;;
- : int = 200

Install is two commands, and the Lwt variant is a separate package:

1
2
opam install ezcurl        # synchronous
opam install ezcurl-lwt    # Lwt-flavoured, depends on ezcurl

Ezcurl.make () returns a client you pass back as ~client to reuse connections. That is the whole performance story: one client, many calls, libcurl keeps the pool. What you give up is streaming — the wrapped API returns a materialised response with body, headers, and code, so a 2 GB download becomes a 2 GB string unless you drop to ocurl.

piaf — The Eio Native

piaf 0.2.0 is the only client here written from scratch for OCaml 5’s Eio. Its README is blunt: “Piaf is a client library for the HTTP/1.X and HTTP/2 protocols written entirely in OCaml.” No libcurl, no Lwt, no conduit. The example in the repo uses Eio.Switch for resource lifetime, which is exactly the pattern you want in a modern OCaml service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
open Piaf

let get_sync env ~sw url =
  print_endline "Sending request...";
  match Client.Oneshot.get ~sw env (Uri.of_string url) with
  | Ok response ->
    if Status.is_successful response.status
    then Body.to_string response.body
    else
      let message = Status.to_string response.status in
      Error (`Msg message)
  | Error e -> failwith (Error.to_string e)

let () =
  Eio_main.run (fun env ->
      Eio.Switch.run (fun sw ->
          match get_sync env ~sw "https://example.com" with
          | Ok body -> print_endline body
          | Error error ->
            let message = Error.to_string error in
            prerr_endline ("Error: " ^ message)))

Two things to notice. First, ~sw is not decoration — every connection is scoped to the switch, so cancelling the switch tears down in-flight requests. Second, Client.Oneshot is the “one request, no pool” path; the persistent client lives elsewhere in the API. Install is one line, and the README warns you to mirror its own resolutions from piaf.opam:

1
opam install piaf

The honest caveat: 0.2.0 means the API is still settling. If you need a client you will not revisit for three years, that is a real risk — this is the one place where cohttp’s decade of backwards compatibility beats technical superiority.

ocurl — The Raw Bindings

ocurl 0.10.1 is “OCaml bindings to libcurl”, and it shows: you create a handle, set options one by one, perform, then read the response buffer. ezcurl exists precisely so you never write this. Reach for ocurl when you need a libcurl capability that ezcurl does not surface — for example a custom CURLOPT_* you cannot otherwise set, or a multi-handle event loop you are driving yourself.

1
opam install curl    # the package name for ocurl

The practical rule: if you are writing more than one Curl.set_* call per request, stop and check whether ezcurl already wraps it. If you are writing a Curl.Multi loop, you are legitimately in ocurl territory and no wrapper will help you.

Timeouts, Connection Reuse, and the Things That Bite in Production

The number one production incident with OCaml HTTP clients is not throughput. It is a request that never returns. Defaults differ per library, and none of them are “safe for a service that must answer in 500 ms”.

  • cohttp: the README has a dedicated “Dealing with timeouts” section because the defaults do not cover the whole request lifecycle. You need both a connect timeout and a body-read timeout; wrapping Client.get in Lwt_unix.with_timeout cancels the wait but does not always close the socket, so long-lived processes leak file descriptors if you retry aggressively.
  • ezcurl: timeouts are libcurl options, so set CURLOPT_TIMEOUT_MS/CURLOPT_CONNECTTIMEOUT_MS on the client at construction. Because one Ezcurl.make () client reuses the connection pool, per-client timeouts are the correct granularity — per-request timeouts force new connections.
  • piaf: cancellation flows from the Eio.Switch. This is the cleanest model of the four: a request that outlives its switch is cancelled, not leaked.
  • ocurl: you own everything, including forgetting to call Curl.cleanup.

Connection reuse is the second trap. cohttp’s default Client.get opens a fresh connection unless you use the call-based API with a shared ctx; ezcurl reuses automatically per client; piaf’s persistent client does, Oneshot does not. On a 50 ms-latency internal API, moving from fresh connections to a pool is routinely a 2-3x throughput difference — far more than any parser micro-optimisation.

Performance: Where Each One Actually Wins

Nobody publishes a credible cross-library benchmark for OCaml HTTP clients, and you should distrust anyone who does without showing their harness. What can be said from the architectures is more useful:

Parsing. cohttp’s Http module is a hand-written parser with no dependencies, designed so other libraries can reuse it. If you are parsing millions of small responses, cohttp’s parser is the most optimised pure-OCaml path. piaf uses its own HTTP/2 framing and is the only one that avoids a second TLS round trip on multiplexed connections.

TLS. libcurl (ezcurl, ocurl) carries the most hardened TLS in existence and gets security patches without you rebuilding OCaml. ocaml-tls (cohttp, piaf) keeps everything in-process and auditable but has a smaller contributor base.

Startup and image size. A statically linked cohttp or piaf binary runs on scratch. ezcurl and ocurl need libcurl.so plus its TLS chain — typically 3-10 MB of extra layers and a wider CVE surface to patch.

Concurrency. For 1,000 concurrent requests against one host, the difference is not the client but the effect system. Use the concurrency model article linked below before benchmarking clients against each other.

Migration Notes: 2019-Era Code in 2026

If you inherit an OCaml service from the Lwt era, three changes will bite:

  1. Cohttp_lwt.Body.to_string returns a promise, not a string, and it consumes the body. Call it once.
  2. TLS selection moved to conduit. Adding lwt_ssl changes the backend order; pin CONDUIT_TLS=native if you need pure OCaml TLS.
  3. Cohttp_eio exists now. You do not need to port to piaf to escape Lwt if the surrounding code is already Lwt-shaped — but do not run two schedulers in one process hoping for the best.

If you are moving to OCaml 5 with Eio, the migration advice is the opposite: do not port cohttp-lwt-unix. Write the outbound layer against piaf, keep the boundary at your own module signature, and let the old Lwt code die with the old service.

For the surrounding ecosystem, our OCaml web frameworks comparison covers the server side of the same decision, the Lwt vs Eio vs Async analysis explains why the scheduler choice dominates, and our OCaml database libraries guide shows the same Lwt/Eio split one layer down in the stack.

FAQ

Which OCaml HTTP client should a beginner start with? ezcurl. Ezcurl.get ~url () returns a result with body, headers, and code, and it follows redirects by default. You can learn the rest of the ecosystem once you have something working.

Is cohttp fast enough for production? Yes, and it is the most widely deployed option in the ecosystem. The bottleneck in real services is almost always connection reuse and timeouts, not the parser. Use the shared-client API rather than calling Client.get per request.

Does piaf support HTTP/2 without a C library? Yes. piaf implements HTTP/1.x and HTTP/2 in OCaml with ocaml-tls for HTTPS, which is why it is the only pure-OCaml option that multiplexes requests over one connection.

Can I use ezcurl without installing libcurl? No. ezcurl wraps ocurl, which binds libcurl; both need the C library and its TLS backend at build and run time. If that is unacceptable, use cohttp or piaf.

Why does cohttp pick ocaml-ssl when both TLS libraries are installed? conduit selects ocaml-ssl by default when present. Set CONDUIT_TLS=native to force ocaml-tls and keep a pure-OCaml dependency graph.

Do these libraries include a server, or only a client? Only cohttp ships a server (Cohttp_lwt_unix.Server, Cohttp_eio.Server). piaf, ezcurl, and ocurl are client-only, so a service that both serves and calls needs cohttp or a separate server framework.


💰 想测试你的市场判断力?我用 Polymarket 做预测市场交易——这是全球最大的预测市场平台,从大选结果到技术监管时间线,什么都可以押注。和赌博不同,这是真正的信息市场:你懂的信息越多,胜率越高。我靠预测技术相关事件的走向已经赚了不少。用我的邀请链接注册:Polymarket.com