October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Single Flight in Gleam: Managing Processes with OTP

Gleam’s singleflight package shares the result of overlapping work for the same key. Learn its fetch outcomes, process model, supervision, and naming cautions.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Gleam’s singleflight package coalesces overlapping requests for the same key: one worker performs the work, and concurrent callers share its result. It is not a cache, and failures or timeouts still need handling. This guide shows how the package fits into Gleam’s typed process APIs and OTP supervision model, using the package documentation for version 1.1.0 and gleam_erlang process documentation for version 1.3.0.

What single flight does—and what it does not

When several callers request the same key at roughly the same time, single flight arranges for the underlying work to run once and shares its result with those callers. For example, multiple requests for the same user profile could share one in-progress fetch rather than each starting an identical fetch.

As an Amazon Associate I earn from qualifying purchases.

This only concerns overlapping work. The package documentation does not establish that a result is stored for later, independent requests; use a cache when you need longer-lived reuse. The Gleam singleflight documentation describes the package as request deduplication and documents its API at version 1.1.0.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the package’s fetch API

The documented setup creates a process name, configures the singleflight actor, starts it, then calls fetch with a key and a function that performs the work. The following follows that API’s shape; adapt imports and the work function’s concrete type to the values your application fetches.

import gleam/erlang/process.{type Name, Name, Subject}
import singleflight

pub fn start_singleflight() {
  let name: Name(singleflight.Message(String)) =
    process.new_name("profile-singleflight")

  let config = singleflight.default_config(name)
  singleflight.start(config)
}

pub fn get_profile(flights, user_id: String) {
  case singleflight.fetch(flights, user_id, fn() {
    load_profile(user_id)
  }) {
    Ok(profile) -> Ok(profile)
    Error(singleflight.Crashed) -> Error("profile worker or actor crashed")
    Error(singleflight.TimedOut) -> Error("profile request timed out")
  }
}

Treat the snippet as an API illustration rather than a complete application: the exact message and value types depend on the package’s exported types and the work your program performs. In production, make the fetch timeout part of an explicit policy, and decide how callers should react to either error.

Handle each outcome deliberately

  • Success: use the returned value just as you would the result of the underlying work.
  • Crashed: the package documents this when the actor or worker exits before producing a value. Decide whether to report the failure, retry under controlled conditions, or return an application-level error.
  • TimedOut: no reply arrived within the configured fetch timeout. A timeout does not prove the work stopped; ensure your surrounding system can tolerate late completion or retry behavior.

These are typed error cases in singleflight.fetch. Do not assume the lower-level process call API has the same failure behavior: gleam_erlang documents panic cases for calls when a callee exits, does not reply in time, or a named subject is unregistered.

How Gleam processes and actors fit in

A BEAM process is the underlying concurrency primitive. Gleam’s process APIs use typed subjects: a subject is a typed destination for messages, and the process that owns it can receive those messages. A request-reply call builds a request containing a reply subject, sends the request, and waits for a response up to a timeout.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An actor adds a stateful message-handling loop: it repeatedly receives messages and updates or uses its state. The Gleam actor interface is designed to make message handling type-safe. The current Gleam OTP project describes actors as the common process type and notes their handling of OTP system messages used for debugging and tracing. See the Gleam OTP project and the gleam_erlang process documentation for the respective project and process API details.

Level What it provides What remains your responsibility
Raw process messaging Typed subjects and message passing between processes. Receiving, state management, request-reply flow, and failure policy.
Actor A higher-level stateful process that handles messages in a loop. Choosing state, message behavior, lifecycle, and how callers handle failures.
singleflight Coalescing concurrent work associated with the same key. Work semantics, timeout policy, error handling, and any persistent caching.

Gleam OTP offers typed APIs for core OTP concepts on the BEAM and is intended to interoperate with Erlang’s OTP framework. It is a useful typed subset, not a separate replacement for OTP or a promise of full feature parity: the project says not all Erlang/OTP functionality is included and some supervision strategies remain in development.

Put long-lived processes under supervision

A supervisor starts and monitors child processes. When a child crashes, a supervisor can restart it; supervisors can themselves be children, forming a supervision tree. Gleam’s introductory supervision example places database, monitoring, and HTTP-handling workers under a supervisor. See the Gleam supervision introduction.

In an application, make the ownership and restart boundary explicit. Start the singleflight process as a supervised child alongside the other long-lived workers that need it, using the child-start and supervisor APIs supported by your installed Gleam OTP version. The following is a structural sketch, not a drop-in child specification:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
pub fn start_app() {
  let flights = start_singleflight()

  supervisor.start([
    database_worker(),
    monitoring_worker(),
    http_worker(flights),
  ])
}

On restart, supervision reconstructs the process structure; it does not preserve the crashed process’s in-memory state. Any in-flight deduplication state owned by a crashed process is therefore not guaranteed to survive. Keep durable data outside transient process memory when it must survive a restart, and make callers able to handle a failed in-flight request.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Process names, ordering, and timeouts

Create names during startup

Named process APIs can make a process discoverable, but Gleam’s process documentation warns that generated names use Erlang atoms. Creating names repeatedly in loops or on restart paths can consume atoms; excessive atom creation can exhaust the atom table and crash the VM. Create a bounded set of names during application startup and pass them to the processes that need them.

Do not infer global message ordering

The documented ordering guarantee applies to messages sent by one process to another. It does not establish a global ordering across messages from multiple senders. If application logic depends on ordering, define how competing senders are coordinated rather than relying on a single shared sequence.

Choose timeouts with the failure mode in mind

A process call waits for a reply up to its requested timeout, but the lower-level gleam_erlang call can panic on timeout, callee exit, or an unregistered named subject. The singleflight API instead documents Crashed and TimedOut result errors for its fetch operation. Keep those API distinctions visible in your error handling, and make timeout and retry policies explicit for the work being coalesced.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Learning OTP alongside Gleam

Gleam OTP’s project documentation describes its goals as “Full type safety of actors and messages” and “Be compatible with Erlang’s OTP actor framework.” Those are project goals, not independent performance findings. The project also notes that its OTP documentation is limited and advises readers to study the framework. The Gleam process introduction is useful for the actor and process concepts, but older tutorial examples may need adaptation to current package APIs.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.