The Depth Counter Pattern: Nestable Batch Operations

How to implement nestable batch operations that defer side effects until the outermost batch completes. A pattern using depth counters and unwind-protect that's surprisingly tricky to get right.