RAII and Deterministic Cleanup
A programming pattern where acquiring a resource (memory, a file handle, a lock) is tied to an object's lifetime, so the resource is automatically released the instant that object goes out of scope.
RAII stands for "resource acquisition is initialization," and the idea is simpler than the name: wrap anything that needs cleanup — a lock on a shared data structure, an open file, a block of memory — inside an object, so that acquiring the resource happens when the object is created and releasing it happens automatically when the object is destroyed. There's no separate "please remember to clean this up" step for the programmer to forget.
This matters in a trading system because forgetting to release a lock or close a connection under an error path is exactly the kind of bug that only shows up under rare conditions, like a market-data feed dropping mid-message, and can hang or crash a live process. With RAII, if a function exits early because of an exception, the object holding the lock still goes out of scope on the way out, and its destructor releases the lock immediately and deterministically — no garbage collector pass required, no explicit finally block to remember.
The pattern is most associated with C++, where object lifetimes are precisely scoped, but the same idea appears as context managers in Python (with open(...) as f) and defer in Go.
RAII ties a resource's release to an object's destructor, so the resource is freed automatically and deterministically the moment the object leaves scope — even on an error path — without relying on manual cleanup code or a garbage collector.
Practice in interviews
Further reading
- Stroustrup, The C++ Programming Language