Resource Lifecycle and Isolation in Multi-Tenant Allocation
System DesignModel answerLast updated
Design entities, state machine, and concurrency control for a resource allocator where tenants share infrastructure but remain strictly isolated.
You're designing the internal module for a multi-tenant platform where users request and release allocatable units—think seats, slots, or licenses. The module must guarantee two properties: no unit is ever assigned to multiple holders simultaneously, and one tenant's users can never interact with another tenant's resources, even by accident or malicious intent.
Your design should demonstrate clean domain modeling, an explicit lifecycle for each unit showing legal state transitions, safe handling of concurrent requests through optimistic locking, and structural enforcement of tenant boundaries within the code itself.
What You Need to Address
Entities and Ownership
Identify the core domain objects, their attributes and relationships, and where tenant identity lives. Show the service and repository boundaries.
Lifecycle State Machine
Define every state a resource passes through, the operations that trigger transitions, and how illegal transitions are rejected—for instance, releasing a unit that was never allocated or is already free.
Concurrency Control
Two users from the same tenant request the last available unit at the same moment on different service nodes. Walk through your optimistic locking mechanism: what each caller receives, how version conflicts are detected, and what happens under heavy contention when many compete for few resources.
Tenant Isolation
Demonstrate how your design structurally prevents any code path from reading or modifying another tenant's data, even if a caller supplies a cross-tenant identifier.
Constraints
- Treat a resource as a generic allocatable entity with an ID and owning tenant.
- Multiple service instances share one transactional store; in-process locks alone are insufficient.
- Use optimistic concurrency control, but note when you would choose pessimistic locking instead.
Questions to Consider
- Does each tenant own a separate pool, or do they draw from shared inventory with per-tenant quotas?
- Can one user hold multiple resources? Are there per-user or per-tenant limits?
- When no resources are available, should requests fail immediately or queue?
- Do allocations expire if never released?
- Should the module retry version conflicts internally or surface them to the caller?
Hints
Hint 1
Consider carrying a version counter on each resource record and using a compare-and-swap write to claim it
Hint 2
State transitions can be validated by maintaining an explicit allowed-transition map and checking before every write
Hint 3
Derive the tenant context once at the service boundary, then thread it through every query and write so repositories never see cross-tenant data
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
A strong candidate walks through a layered design that separates concerns cleanly and enforces invariants at compile time where possible, runtime where necessary.
Part 1: Entity Model and Boundaries
Core Entities
class Tenant {
UUID tenantId;
String name;
}
class Customer {
UUID customerId;
UUID tenantId; // foreign key, indexed
String email;
}
class Resource {
UUID resourceId;
UUID tenantId; // indexed for isolation
ResourceState state;
UUID currentHolder; // nullable, the customer holding it
Instant allocatedAt;
Instant expiresAt; // nullable, for lease expiry
long version; // optimistic lock
}
enum ResourceState {
AVAILABLE, ALLOCATED, RESERVED, RETIRED
}
Every tenant-scoped entity carries tenantId. The Resource entity holds both lifecycle state and the version counter for concurrency control.
Service and Repository
interface AllocationService {
Resource allocate(TenantContext ctx, UUID customerId)
throws NoResourcesAvailableException, TenantMismatchException;
void release(TenantContext ctx, UUID customerId, UUID resourceId)
throws IllegalStateException, TenantMismatchException;
}
interface ResourceRepository {
Optional<Resource> findAvailableForTenant(UUID tenantId);
boolean tryAllocate(UUID resourceId, UUID customerId,
Instant expiresAt, long expectedVersion);
Resource getByIdAndTenant(UUID resourceId, UUID tenantId);
}
The TenantContext is derived once at the API gateway or service entry and flows through every call. Repositories accept tenantId explicitly, making cross-tenant queries structurally difficult.
Part 2: Lifecycle State Machine
States and Transitions
| Current State | Operation | Next State | Validation |
|---|---|---|---|
| AVAILABLE | allocate | ALLOCATED | holder must be null |
| ALLOCATED | release | AVAILABLE | holder matches caller |
| ALLOCATED | expire | AVAILABLE | expiresAt in past |
| AVAILABLE | retire | RETIRED | admin action |
| RETIRED | — | — | terminal |
Enforcement
class ResourceStateMachine {
private static final Map<ResourceState, Set<ResourceState>> ALLOWED = Map.of(
AVAILABLE, Set.of(ALLOCATED, RETIRED),
ALLOCATED, Set.of(AVAILABLE),
RETIRED, Set.of()
);
public void validateTransition(ResourceState from, ResourceState to) {
if (!ALLOWED.get(from).contains(to)) {
throw new IllegalStateTransitionException(from, to);
}
}
}
Before applying any state change, the service validates the transition. Releasing an already-available resource or allocating a retired one fails immediately with a clear error.
Handling Edge Cases
- Double release: The second call finds
state=AVAILABLEandholder=null, so validation rejects the transition. - Expiry racing with release: Both attempt
ALLOCATED → AVAILABLE. One succeeds via optimistic lock; the other retries, sees the resource already available, and considers the release complete (idempotent outcome).
Part 3: Optimistic Locking Under Concurrency
Allocation Flow
- Query:
SELECT * FROM resources WHERE tenant_id = ? AND state = 'AVAILABLE' LIMIT 1 - Load current
version(e.g.,version=5). - Attempt conditional write:
UPDATE resources SET state = 'ALLOCATED', current_holder = ?, allocated_at = ?, expires_at = ?, version = version + 1 WHERE resource_id = ? AND version = 5 - If
rowsAffected = 0, another transaction incremented the version first. Retry from step 1, up to three attempts. - After exhausting retries, return
NoResourcesAvailableException.
What Each Caller Sees
- Caller A:
UPDATEsucceeds, receives the resource. - Caller B:
UPDATEreturns zero rows. Retry finds either another available resource or sees the pool empty and fails cleanly.
When to Switch to Pessimistic Locking
Optimistic locking works well when contention is low to moderate. When retry rates exceed ~20%, or when allocation latency spikes due to repeated retries, switch to SELECT ... FOR UPDATE to serialize access to the candidate resource before committing. Trade-off: lower throughput under light load, but predictable latency under heavy contention.
Contention Hot Spots
If all tenants draw from one global pool, the first available row becomes a hot spot. Mitigate by:
- Sharding pools by tenant (each tenant owns a slice).
- Randomizing the selection query to spread contention.
- Using a reservation pattern: mark a resource
RESERVEDfirst with a short TTL, then promote toALLOCATEDafter caller confirms.
Part 4: Structural Tenant Isolation
Deriving Tenant Context
At the API gateway or authentication filter, extract tenantId from the JWT or session and construct a TenantContext that flows through the call stack. Never re-derive it from user input.
@RestController
class AllocationController {
@PostMapping("/allocate")
Resource allocate(@AuthenticatedTenant TenantContext ctx,
@RequestBody AllocateRequest req) {
// ctx.tenantId is already validated by the framework
return allocationService.allocate(ctx, req.customerId);
}
}
Repository Design
Every query must include tenantId in the WHERE clause. Make it structurally enforced:
interface ResourceRepository {
// No method signature omits tenantId
Resource getByIdAndTenant(UUID resourceId, UUID tenantId);
List<Resource> findAvailableForTenant(UUID tenantId, int limit);
}
If a caller accidentally passes the wrong tenantId, the query returns empty or throws NotFoundException. The resource is never visible.
Defense in Depth
- Database: Row-level security policies filter every query by
tenant_idautomatically (PostgreSQL RLS, for example). - Indexes: Composite indexes on
(tenant_id, state, resource_id)make cross-tenant scans impossible to execute efficiently. - Auditing: Log every allocation and release with
tenantIdandcustomerIdfor forensic review.
Testing Isolation
- Create two tenants, allocate resources to each.
- Attempt to release Tenant A's resource using Tenant B's context; assert
TenantMismatchException. - Run a background thread that attempts raw SQL injection of another
tenantId; verify the query returns zero rows or the RLS policy blocks it.
Trade-Offs and Design Choices
| Choice | Benefit | Cost |
|---|---|---|
| Optimistic locking | High throughput under low contention | Retries add latency under heavy load |
| Explicit state enum | Compile-time safety, clear contracts | Requires migration to add new states |
| Lease expiry | Auto-recovery from stuck clients | Background job overhead, clock skew risk |
| Per-tenant pools | Perfect isolation, no cross-tenant contention | Stranded capacity when one tenant under-utilizes |
When to Use Pessimistic Locking
When allocation requests arrive in bursts (e.g., a course registration opening) and retry storms degrade performance, or when the transaction includes multiple coordinated writes and you need serializable isolation.
Common Mistakes
- Forgetting to filter by
tenantIdin a repository method, opening a cross-tenant leak. - Retrying infinitely on version conflicts instead of bounding attempts.
- Using only in-process locks in a horizontally scaled service.
- Treating state as a string and validating transitions with ad hoc
ifstatements instead of a transition map.
A strong answer demonstrates that concurrency control and tenant isolation are not afterthoughts—they are baked into the type signatures, the state machine, and the persistence layer from the start.