lwt

Lwt

Cooperative threading library for OCaml providing promises and async I/O

Details

Language / Topic
ocamlOCaml
Category
framework
Compatible Frameworks
lwt
Source
ocsigen

Rules

balanced
- Use `let*` (bind syntax) with `open Lwt.Syntax` for sequential async operations instead of explicit `>>=` chains — `let* result = some_lwt_value in ...` reads as straight-line code and composes cleanly.
- Use `Lwt.both` to run two independent async operations concurrently and wait for both; use `Lwt.pick` to race them and take only the first to complete — never `bind` sequential operations that have no data dependency.
- Always handle `Lwt.catch` around I/O operations that may throw — uncaught exceptions inside Lwt threads are silently dropped unless a rejection handler is attached.
- Model cancellable operations with `Lwt.task ()` which returns `(promise, resolver)` — call `Lwt.cancel promise` to cancel, and handle `Lwt.Canceled` in a `Lwt.catch` if cleanup is needed.
- Avoid `Lwt_main.run` inside library functions — it blocks the calling thread until the promise resolves and must only be called from the program entry point to start the event loop.
- Use `Lwt_pool.use pool (fun conn -> ...)` for connection pools — it automatically checks out, uses, and returns the connection, handling pool exhaustion by queuing waiters.