Skip to content

using, await using and Symbol.dispose

Relay’s worker opens a database connection and takes a lock for every job. If the job throws, both must still be released. A leaked connection is a slow bug: the worker runs fine for hours, then the pool is empty and every job waits.

The usual fix is try and finally. It works, but it is easy to forget, and with two resources it nests. This lesson uses the language feature built for it: using. Nothing here needs a library.

Each resource needs its own try/finally, and the order of the finally blocks is something you have to get right by hand:

interface Connection {
query(sql: string): string
close(): void
}
declare function open(name: string): Connection
function runJob(): string {
const conn = open("db")
try {
return conn.query("select 1")
} finally {
conn.close()
}
}

If someone adds a second resource and forgets the try, the first one leaks on a throw. The compiler cannot see that.

An object is disposable when it has a method under the key Symbol.dispose. The built-in Disposable interface describes it. A using declaration calls that method when the scope ends:

const log: string[] = []
function open(name: string): Disposable & { query(sql: string): string } {
log.push(`open ${name}`)
return {
query: (sql) => `${name}: ${sql}`,
[Symbol.dispose]() {
log.push(`close ${name}`)
},
}
}
function runJob(): string {
using conn = open("db")
return conn.query("select 1")
} // conn is closed here, on return or on throw

The scope can be a function, a block or a loop body. The compiler only accepts using on a value that has Symbol.dispose (or null and undefined, which are skipped). A plain object with a close() method is rejected:

declare const plain: { close(): void }
// @ts-expect-error: no [Symbol.dispose] method
using conn = plain

Resources are disposed in the reverse order of declaration. The one declared last is released first, because it may depend on the earlier ones. A lock taken while holding a connection is released before that connection closes:

declare function open(name: string): Disposable
declare function lock(key: string): Disposable
function run() {
using db = open("db")
using held = lock("job-1")
// ... work ...
} // held is released first, then db

This is the same rule as nested try/finally, but you cannot get it wrong by moving a line.

using disposes on every exit: return, a throw, or falling off the end. The error still propagates after the cleanup runs.

If the disposal method itself throws while an error is already in flight, the language does not drop either one. It throws a SuppressedError. Its error is the new disposal failure and its suppressed is the original error:

declare const broken: Disposable
function run() {
using res = broken
throw new Error("job failed")
}
try {
run()
} catch (e) {
if (e instanceof SuppressedError) {
console.log(e.error) // the failure from disposing
console.log(e.suppressed) // Error: job failed
}
}

Without this, a failing close() would hide the real reason the job failed.

Releasing a lock often needs a network call or a flush. For that, an object has Symbol.asyncDispose, which returns a promise, and you declare it with await using. The interface is AsyncDisposable. await using only works inside an async function or at the top level of a module:

interface Lock extends AsyncDisposable {
readonly key: string
}
declare function acquireLock(key: string): Promise<Lock>
declare function open(name: string): Disposable
async function runJob(jobId: string) {
using db = open("db")
await using lock = await acquireLock(jobId)
return `locked ${lock.key}`
} // lock is awaited and released, then db closes

You can mix using and await using in one scope. Order is still reverse across both. Note the two awaits on the lock line: the first waits for the lock to be taken, the second (in await using) is the disposal at the end of the scope.

DisposableStack for owned and conditional resources

Section titled “DisposableStack for owned and conditional resources”

using ties a resource to a scope. Sometimes a function must acquire a variable number of resources, or hand them to its caller. DisposableStack and AsyncDisposableStack collect resources and dispose them all later, in reverse order:

interface Lock extends AsyncDisposable {
readonly key: string
}
declare function acquireLock(key: string): Promise<Lock>
async function lockAll(keys: readonly string[]): Promise<AsyncDisposableStack> {
await using stack = new AsyncDisposableStack()
for (const key of keys) stack.use(await acquireLock(key))
return stack.move()
}
async function main() {
await using held = await lockAll(["a", "b", "c"])
// work with a, b and c held
} // unlocked c, b, a

stack.use(x) registers a resource and returns it. stack.move() moves everything into a new stack and leaves the old one empty. That is the key line. If the third acquireLock throws, stack is still full when the function exits, so await using releases the first two. If the loop finishes, move() empties it first, so nothing is released and the caller now owns the locks.

Not every cleanup is a scope. A connection pool that lives for the whole process does not need using: it is closed once, by the shutdown code. Use using for resources whose lifetime is one function call or one job. And if a resource must outlive the function that created it, return it (or return a stack with move()) instead of disposing it.

Make Connection disposable and Lock async-disposable, then rewrite runJob and lockAll. The starter closes things by hand: a throw leaks them and the order is wrong. The tests read an event log to check the order and the cleanup on error.

  • A Symbol.dispose method makes an object Disposable. using calls it when the scope ends.
  • Disposal runs on return and on throw, in reverse order of declaration.
  • If disposal throws while an error is in flight, you get a SuppressedError with both.
  • await using and Symbol.asyncDispose are the async versions, for locks and flushes.
  • DisposableStack owns a dynamic set of resources. move() hands them to the caller on success.
  • Use it for call-scoped resources, not for things that live as long as the process.