SingleFlight: The Small Pattern That Quietly Saves Your Application Performance

In modern application development — whether backend APIs or frontend data fetching — you sometimes face many concurrent requests for the same resource. Without careful handling, this can lead to:
- Excessive load on databases or external services
- Duplicate function executions
- Rate limit or performance issues
A smart solution to this is the SingleFlight pattern — not often talked about — but very valuable.
What Is SingleFlight?
SingleFlight ensures that when an asynchronous operation is already in-flight (running) for a given key, additional concurrent calls with the same key don’t trigger a new execution. Instead, they wait for the first execution and share its result.
If that line is invoked 10 times concurrently with "user-123", only one real API/db call runs — and all callers get the same result.
Flyonce Package Overview
flyonce is a TypeScript library develop by wahyu agus arifin, that implements SingleFlight with optional caching. It works with Bun, Node.js, Deno, and other JavaScript runtimes.
Key Features:
- SingleFlight deduplication per key
- Optional result caching with TTL
- Graceful error handling
- Zero dependencies, lightweight
- High performance and concurrency-aware
Contoh
Only one actual API call will run for the key "user-123".
Real-World Use Cases
SingleFlight (and flyonce) is especially helpful for:
- API rate limiting & de-duplication
- Heavy or expensive database queries
- Microservice call optimization
- Cache stampede protection
- Concurrent data fetching in frontends
Without it, concurrent calls will execute independently — wasting CPU, memory, and bandwidth.
Benefits
- Reduces redundant work
- Improves performance
- Ensures consistency
- Easy to integrate
Conclusion
The SingleFlight pattern is a clever way to deduplicate async operations. The flyonce library makes it practical with caching and a clean API. Whether you’re building server systems or frontend apps, flyonce can help keep performance tight and resource usage low.