r/typescript • u/acefolio_dev • 17h ago
How do you stop a singleton service from holding per-request state?
I've been building a small DI layer for Elysia on Bun, and one bug class I wanted the container to catch is a long-lived service holding onto something that only makes sense for one request, like the current user or a request id. It looks fine with one request at a time and then two concurrent requests start seeing each other's data.
The approach I went with: each class declares its lifetime and its dependencies as static fields, and the graph refuses to build if a singleton depends on a request-scoped provider.
```ts
class RequestAudit {
static readonly lifetime = "request" as const;
}
class ReportService {
// singleton by default
static readonly needs = [RequestAudit] as const; // the graph rejects this
constructor(private readonly audit: RequestAudit) {}
}
```
Routes that need per-request things get them through a handler wrapper instead, so request-scoped objects never end up stored on a singleton.
Curious how others handle this in Node or Bun backends. Do you lean on AsyncLocalStorage, pass a context object around explicitly, or have your container enforce it? And is a hard error too strict for cases where someone actually wants it?
It's alpha (0.1.x), so the API may still change. Docs if anyone wants to look: https://elpod.vercel.app/docs/dependency-injection