Design a Resource Management System

0%

Editorial Solution

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Resource Hierarchy

ResourceLoader Hierarchy

ResourceHandle as a Generic Wrapper

Design Patterns

Strategy Pattern: Loader Selection

Object Pool / Flyweight: Shared Resource Instances

Proxy Pattern: ResourceHandle

Observer Pattern: Async Load Notifications

Define Class Members (write code)

Enums

Resource (Abstract Base)

Concrete Resources: Texture and Shader

ResourceHandle with Atomic Reference Counting

ResourceLoader Interface and Implementations

ResourceCache with LRU Eviction

ResourceManager (Singleton Orchestrator)

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Resource Loading: The Core Concurrency Challenge

LRU Eviction Respecting Active References

Scaling Beyond a Single Instance

Create/Explain your diagram(s)

Future improvements

Table of Contents

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Resource Hierarchy

ResourceLoader Hierarchy

ResourceHandle as a Generic Wrapper

Design Patterns

Strategy Pattern: Loader Selection

Object Pool / Flyweight: Shared Resource Instances

Proxy Pattern: ResourceHandle

Observer Pattern: Async Load Notifications

Define Class Members (write code)

Enums

Resource (Abstract Base)

Concrete Resources: Texture and Shader

ResourceHandle with Atomic Reference Counting

ResourceLoader Interface and Implementations

ResourceCache with LRU Eviction

ResourceManager (Singleton Orchestrator)

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Resource Loading: The Core Concurrency Challenge

LRU Eviction Respecting Active References

Scaling Beyond a Single Instance

Create/Explain your diagram(s)

Future improvements

A resource management system sounds simple: load a file, hand it to the game engine, done. But in a real game, hundreds of systems request the same texture simultaneously, memory budgets are tight, assets depend on each other, and the game loop cannot stall while a 50 MB model loads from disk. Let's break down what the system actually needs to do.

Interview Dialogue

CandidateWhat types of game resources should the system manage?
InterviewerClick to reveal answer
CandidateShould resources be cached after loading, or reloaded from disk each time?
InterviewerClick to reveal answer
CandidateWhat happens when the memory budget is exceeded?
InterviewerClick to reveal answer
CandidateShould loading happen synchronously or on a background thread?
InterviewerClick to reveal answer
CandidateIs hot-reloading of assets during development in scope?
InterviewerClick to reveal answer
Show all answers

Functional Requirements

  1. Asset Loading by Type: Load game assets from disk or network. Each resource type has its own loading pipeline: textures decode PNG or DDS files, models parse OBJ or FBX meshes, audio clips decode WAV or OGG, and shaders compile GLSL source. The system must route each load request to the correct loader.
  2. Resource Caching: Once loaded, resources are cached in memory so subsequent requests for the same asset return instantly without re-reading from disk. Resources are keyed by a unique identifier (file path or generated ID).
  3. Reference Counting: Track how many game objects are actively using each resource via an atomic reference count. When the count drops to zero, the resource becomes eligible for eviction. This prevents premature unloading while a system still holds a reference.
  4. Asynchronous Loading with Callbacks: Resources load on a background thread with completion callbacks. The game loop continues rendering while assets load. Loading screens subscribe to progress events to display a percentage bar.
  5. Memory Budget Enforcement with LRU Eviction: The system enforces a configurable memory budget (e.g., 512 MB). When loading a new resource would exceed the budget, the least-recently-used unreferenced resources are evicted to make room.

Non-Functional Requirements

  • Thread Safety: Multiple game systems may request the same resource concurrently. The cache and reference counting must be thread-safe. Without synchronization, two threads could both see a cache miss, both load from disk, and two copies end up in memory.
  • Extensibility: New resource types (e.g., animation clips, particle definitions) can be added by implementing a new loader without modifying the core manager.
  • Low Latency: Cache hits should return in microseconds. Only cache misses trigger disk or network I/O.

Let's trace a resource request from start to finish and see where the objects emerge naturally.

Start by scanning the requirements for nouns. "Game resources like textures, models, audio clips" gives us the Resource hierarchy. "Resource cache with memory budget" becomes ResourceCache. "Reference counting for active users" maps to ResourceHandle. "Loading pipeline per resource type" gives us ResourceLoader. Not every noun becomes a class. "memory budget" is a configuration field on the cache, not its own entity, but nouns give you the starting lineup.

A game level begins loading. The engine requests "goblin_texture.png". Right away we need a Resource abstraction. But textures decode pixel data, models parse vertex buffers, shaders compile GLSL, and audio clips decode waveforms. Putting all of that into one class would create a monster. So Resource is abstract, with concrete subclasses: Texture, Model, AudioClip, Shader. Each knows how to load() and unload() itself.

Now, who actually loads the resource from disk? The Resource class knows its own data format, but the loading pipeline involves file I/O, format detection, and error handling. This is where ResourceLoader comes in. It is an interface with one key method: load(String path). TextureLoader decodes images, ShaderLoader compiles shader source, AudioLoader decodes audio streams. Each loader registers which ResourceType it supports. The ResourceManager picks the right loader using a type-to-loader map. This is the Strategy pattern: the loading algorithm is selected at runtime based on the resource type.

Once loaded, the resource goes into the ResourceCache, an LRU cache keyed by resource ID. The cache tracks total memory usage and enforces the budget. When memory runs tight, it evicts the least-recently-used resource that has zero active references. The cache uses ConcurrentHashMap for lock-free reads on cache hits.

But how do we know if a resource is still in use? This is where ResourceHandle enters. It is a typed smart pointer wrapping a Resource with an AtomicInteger reference count. Game objects do not hold direct references to Resources. They hold handles. When a system acquires a handle, the count increments. When it releases, the count decrements. At zero, the resource becomes eligible for eviction. The handle also provides access control: calling get() on a released handle throws an exception rather than returning stale data.

For async loading, a LoadRequest encapsulates the request: the path, resource type, priority, a completion callback, and a CompletableFuture for programmatic waiting. The manager submits load requests to a thread pool.

Finally, the ResourceManager is the singleton orchestrator. It holds the loader map, the cache, and the loading thread pool. Its API is simple: load(), loadAsync(), unload(), preload(), hotReload(). It coordinates the pieces but implements no loading, caching, or counting logic itself.

Key Insight

Why a separate Resource class instead of combining its responsibilities into ResourceLoader? Each class should have one reason to change. If ResourceLoader handled both its own logic and Resource logic, a change to either concern would risk breaking the other.

The relationships in the resource management system reveal important ownership and lifecycle decisions.

Does the ResourceManager own the ResourceCache, or just use it?

The cache exists solely to serve the manager. It is created during manager initialization and destroyed when the manager shuts down. No other component accesses the cache directly. That is composition: ResourceManager owns ResourceCache.

Does the ResourceHandle own the Resource?

This is subtle. The handle wraps a resource and provides access, but the resource's lifecycle is controlled by the cache. Multiple handles can point to the same resource (when different systems acquire separate handles). The handle does not create or destroy the resource; it merely increments and decrements a reference count. When the count hits zero, the handle notifies the manager, but eviction is the cache's decision. This is the Proxy pattern: the handle controls access without owning the underlying object.

How does the Strategy pattern connect ResourceManager to ResourceLoader?

The manager holds a Map<ResourceType, ResourceLoader<?>>. When a load request arrives, the manager selects the appropriate loader by type. This is association, not composition: loaders are registered externally and can be swapped. The manager does not create loaders; they are injected via registerLoader(). Adding a new loader for a new resource type requires zero changes to the manager's code.

Key Insight

Why not let game objects hold direct Resource references instead of ResourceHandles? Because the cache would have zero visibility into which resources are still in use. Without reference counting, every eviction decision is a blind gamble: evict a texture still rendered by 50 enemies, and the game crashes. The Handle proxy gives the cache exact usage data.

Resources form a dependency DAG:

A Material depends on Texture and Shader resources. The manager loads dependencies first using recursive calls. If a dependency is already cached, it returns immediately. This naturally handles diamond dependencies: if Material A and Material B both depend on the same Texture, the texture is loaded once. The cache prevents evicting a resource that has active dependents, even if its direct reference count is zero.

Observer pattern for async notifications:

Async load requests carry a callback. When loading completes, the callback fires. Loading screens observe progress. The hot-reload system observes file system changes and triggers reload events. The observer relationship is loose coupling: the manager does not know what the callback does; it just calls it.

The resource management system has two clean hierarchies: the Resource type family and the ResourceLoader strategy family.

Resource Hierarchy

The abstract Resource class provides common fields (resourceId, path, type, state, sizeBytes, dependencies, lastAccessTime) and declares abstract methods:

Each concrete subclass fills in the type-specific logic:

  • Texture: Decodes image files (PNG, DDS) into pixel data. Tracks width, height, and format. Memory footprint is width x height x bytes-per-pixel.
  • AudioClip: Decodes audio streams (WAV, OGG) into sample arrays. Tracks sample rate and channel count.
  • Shader: Reads and compiles GLSL source into a GPU program. Splits vertex and fragment sources, compiles via the graphics API.
  • Model: Parses mesh data (vertices, normals, UVs, indices) from 3D file formats.

Why not a single Resource class with a type enum? Because the load/unload logic differs completely: Texture manipulates pixel buffers, Shader calls the GPU compiler, AudioClip decodes waveforms. A type enum would require a switch inside load(), mixing unrelated I/O code. Every new type means modifying the switch, violating OCP.

Key Insight

Why not use a regular HashMap with synchronized methods for the ResourceCache instead of ConcurrentHashMap? Because cache hits happen on every resource access during gameplay, potentially hundreds of times per frame at 60 FPS. Synchronized methods force every read to acquire and release a lock even though reads do not modify state. ConcurrentHashMap provides lock-free reads, keeping the hot path contention-free.

ResourceLoader Hierarchy

The ResourceLoader<T> interface declares two methods:

Implementations: TextureLoader, ShaderLoader, AudioLoader, ModelLoader. Each constructs the appropriate Resource subclass, calls its load() method, and returns it. Loaders register themselves with the ResourceManager via registerLoader(). Adding a new resource type means creating one Resource subclass and one Loader implementation; no existing code changes.

ResourceHandle as a Generic Wrapper

ResourceHandle<T extends Resource> is not part of a hierarchy; it is a generic class parameterized by the resource type. This gives callers type-safe access: ResourceHandle<Texture> returns a Texture from get(), not a raw Resource. The handle's reference counting logic is the same regardless of the resource type.

Let me walk through each pattern by showing what goes wrong without it.

Strategy Pattern: Loader Selection

Without the Strategy pattern, the ResourceManager would contain a switch on resource type:

java
1// Without Strategy - brittle and violates OCP
2if (type == TEXTURE) { /* decode PNG */ }
3else if (type == SHADER) { /* compile GLSL */ }
4else if (type == AUDIO) { /* decode WAV */ }

Every new type modifies the manager. With the Strategy pattern, each loader is a self-contained strategy:

java
ResourceLoader<?> loader = loaders.get(type);
Resource resource = loader.load(path);

The manager does not know or care what the loader does internally. TextureLoader decodes images. ShaderLoader compiles shaders. New loaders register via registerLoader(). The manager's load method never changes.

Key Insight

The Strategy pattern turns loader selection from a maintenance liability into a registration problem. Adding a new resource type becomes a one-line registerLoader() call instead of a risky modification to the manager's core loading logic.

Object Pool / Flyweight: Shared Resource Instances

This is the core value of the entire system. When 100 enemy entities all use "goblin.png", there should be exactly one Texture instance in memory, not 100 copies. The ResourceCache is essentially an object pool: resources are loaded once, cached, and shared. Each user gets a ResourceHandle pointing to the same underlying resource.

Without this pattern, every new Texture("goblin.png") would load from disk, allocate pixel buffers, and consume memory independently. For a 4K texture at 64 MB, 100 copies would consume 6.4 GB. With the pool, it costs 64 MB total, plus the negligible overhead of 100 handles.

Proxy Pattern: ResourceHandle

The ResourceHandle acts as a proxy between game objects and the underlying resource. It provides three services that a direct reference cannot:

  1. Lifetime tracking: Atomic reference counting tells the cache when a resource is safe to evict.
  2. Access control: Calling get() on a released handle throws an exception rather than returning stale or null data.
  3. Lazy loading potential: A handle could be created for an unloaded resource, triggering loading on first get() call.

Without the proxy, game objects would hold raw Resource references. The cache would have no way to know which resources are still in use, making safe eviction impossible.

Common Pitfall

Never let game objects hold direct Resource references. Without the ResourceHandle proxy, the cache has zero visibility into which resources are active, making every eviction decision a gamble between wasting memory and crashing the game.

Observer Pattern: Async Load Notifications

Async load requests carry a callback that fires on completion. The loading screen observes progress without the manager knowing what a loading screen is. The hot-reload system observes file changes and triggers reloads. This decoupling means adding new observers (analytics, debug logging) requires no changes to the manager.

Level Expectations

Junior: identify Strategy and Object Pool as the two core patterns and explain how they prevent code duplication.

Mid-level: demonstrate how the Proxy pattern enables safe eviction through reference counting and discuss the memory math (one 64 MB texture vs 100 copies).

Senior: propose a dependency-aware eviction policy and explain how Observer enables hot-reload without coupling the manager to file-watching infrastructure.

Let's build the resource management system in Java. I will call out the concurrency decisions that matter and the bugs you would hit with simpler alternatives.

Enums

Resource (Abstract Base)

The state field is volatile because background loading threads write it while the main thread reads it. Without volatile, the main thread might cache a stale LOADING value even after the background thread has set it to LOADED.

Concrete Resources: Texture and Shader

ResourceHandle with Atomic Reference Counting

This is where the critical concurrency logic lives. The AtomicInteger ensures that acquire and release are thread-safe without locks. The acquire() method uses increment-then-check to detect use-after-release: if the count was zero before increment, someone is trying to acquire a dead handle.

Interview Tip

In a live interview, walk through the ResourceHandle's acquire/release lifecycle on the whiteboard. Show the AtomicInteger going from 1 to 2 on acquire, back to 1 on release, and explain the edge case when it hits 0 and triggers eviction eligibility. This demonstrates you understand both the API and the concurrency invariant.

ResourceLoader Interface and Implementations

ResourceCache with LRU Eviction

The cache uses ConcurrentHashMap for the main store, giving lock-free reads on cache hits. The evictIfNeeded() method scans for the least-recently-used resource with zero references. Notice it skips resources with active references, preventing eviction of in-use assets.

ResourceManager (Singleton Orchestrator)

The manager uses double-checked locking for singleton initialization. The load() method checks the cache first (lock-free hit), then acquires a per-resource lock on miss to prevent duplicate loads. The loadAsync() method submits work to a thread pool and returns a CompletableFuture.

Run and Test

Browse the complete solution code and run it. Try modifying the code to experiment with the design.

Loading editor...

Single Responsibility Principle

  • ResourceLoader implementations handle type-specific loading logic (decoding images, parsing meshes, compiling shaders).
  • ResourceCache handles storage, LRU tracking, and memory budget enforcement.
  • ResourceHandle handles reference counting and access control.
  • Resource subclasses encapsulate their own I/O format and data structures.
  • ResourceManager orchestrates these components but implements no loading, caching, or counting logic itself.

Each class has exactly one reason to change. If the PNG decoding library changes, only TextureLoader is affected. If the eviction policy changes from LRU to LFU, only ResourceCache changes.

Open/Closed Principle

Adding a new resource type (e.g., AnimationClip) requires creating a new AnimationClip class extending Resource and a new AnimationLoader implementing ResourceLoader. Register it via registerLoader(). No changes to ResourceManager, ResourceCache, or ResourceHandle. The system is open for extension, closed for modification.

Interview Tip

When an interviewer asks 'how would you add a new resource type,' answer with the power phrase 'I add a class and register it. Zero existing code changes.' Then walk through the two new files (AnimationClip and AnimationLoader) and confirm that ResourceManager, ResourceCache, and ResourceHandle are untouched. This is the clearest OCP demonstration in the entire design.

Liskov Substitution Principle

All Resource subclasses honor the load()/unload() contract: they load data from disk, set their memory footprint, and update their state. The cache, handle, and manager all operate on abstract Resource references. Replacing any subclass with another does not break the pipeline. A Texture and a Shader flow through the same loading, caching, and eviction logic identically.

Interface Segregation Principle

The ResourceLoader<T> interface has only two methods: load() and supports(). Implementations are not forced to implement irrelevant methods. If the system needed a separate ResourceValidator or ResourceSerializer, those would be separate interfaces, not added to ResourceLoader.

Dependency Inversion Principle

The ResourceManager depends on the ResourceLoader interface, not on concrete loaders like TextureLoader or ShaderLoader. Loaders are injected via registerLoader(). This allows mock loaders in tests, platform-specific loaders (Vulkan vs. OpenGL), and hot-swappable loaders at runtime. The manager never imports a concrete loader class.

Thread-Safe Resource Loading: The Core Concurrency Challenge

This is the section an interviewer is most likely to probe, because it is where real game engines fail if designed carelessly.

The race condition, made concrete: Thread A and Thread B both request "boss_texture.png" at the same time. Without synchronization, both check the cache, both see a miss, both load from disk, and two copies end up in memory. This wastes memory, violates the single-instance invariant, and can cause subtle bugs (two Texture objects with different internal state).

The solution is a layered locking strategy:

  1. Lock-free cache hits: cache.get() uses ConcurrentHashMap, so the common case (resource already loaded) incurs zero synchronization overhead.
  2. Per-resource lock on cache miss: On a miss, the manager acquires a lock keyed by resource ID. The first thread to acquire the lock loads the resource. The second thread waits, then finds the resource in the cache and returns the existing instance.
  3. Atomic reference counting: ResourceHandle uses AtomicInteger, so acquire/release is lock-free. This is critical because handles may be acquired and released from any thread at any time.

Why not lock the entire cache on miss? Because loading a resource involves disk I/O that may take hundreds of milliseconds. Locking the entire cache would block all other load requests, even for different resources. Per-resource locking allows concurrent loads of different resources while preventing duplicate loads of the same resource.

Key Insight

The layered locking strategy is the key concurrency insight. Lock-free ConcurrentHashMap for the hot path (cache hits), per-resource locks for the cold path (cache misses), and AtomicInteger for handle reference counting. Each layer uses the minimum synchronization needed for its access pattern.

LRU Eviction Respecting Active References

The eviction algorithm must never evict a resource that is still in use. The findLRUUnreferenced() method scans all cached resources, skipping any with refCount > 0. Among the remaining candidates, it selects the one with the oldest lastAccessTime. This ensures that actively used resources are protected, and among unused resources, the stalest one goes first.

Dependency-aware eviction: Before evicting a resource, the system should check whether any loaded resource lists it as a dependency. A Material with active references depends on a Texture; evicting that Texture would corrupt the Material even though the Texture's direct refCount is zero.

Scaling Beyond a Single Instance

Streaming LOD: Load low-resolution versions first (mip level 0), then progressively stream higher-quality versions as the player approaches. This reduces initial load times and keeps memory proportional to visual need.

Asset bundling: Pack related resources into bundles (all assets for a level). Load the entire bundle as a single I/O operation instead of hundreds of small file reads, reducing file system overhead.

Memory budget tuning: Different platforms have different memory constraints (console vs. PC vs. mobile). The configurable memory budget and eviction policy allow the same system to operate across platforms by adjusting the budget at initialization.

Level Expectations

Junior: explain why per-resource locking is needed and describe the duplicate-load race condition.

Mid-level: design the full layered locking strategy and explain dependency-aware eviction with concrete examples.

Senior: propose streaming LOD with progressive mip-chain loading, asset bundling for level transitions, and platform-aware memory budget tuning with runtime telemetry.

Below is the class diagram showing the resource management system architecture.

Key points to highlight in an interview:

  • The Strategy pattern (ResourceManager selects ResourceLoader by type) enables adding new resource types without modifying the manager.
  • The Proxy pattern (ResourceHandle wraps Resource) provides reference counting and access control. The cache uses handle refCounts to make safe eviction decisions.
  • ResourceManager owns ResourceCache (composition) but references ResourceLoader (association, injected via registerLoader).
  • The Resource hierarchy shows clean separation: each subclass handles its own I/O format, and the cache/manager operate on the abstract base.
  • Concurrency primitives are visible in the design: AtomicInteger in ResourceHandle, ConcurrentHashMap in ResourceCache, volatile state in Resource.

Streaming Level-of-Detail (LOD)

Load low-resolution versions of textures and models first (mip level 0), then progressively stream higher-quality versions as the player approaches. Introduce a StreamingManager that monitors camera distance and triggers quality upgrades. This reduces initial load times and keeps memory proportional to visual need. The Resource class would support multiple quality tiers, each with its own memory footprint.

Asset Bundling

Pack related resources into bundles (all assets for a level). Load the entire bundle as a single I/O operation instead of hundreds of small file reads. Introduce an AssetBundle class that contains a manifest of resource IDs and a single compressed archive. The ResourceManager loads from bundles when available, falling back to individual files for unbundled resources.

CDN Loading with Delta Patches

For live-service games, load assets from a content delivery network with local disk caching. Support delta patches so only changed assets are re-downloaded on updates. Introduce a RemoteAssetProvider that checks a local cache first, then fetches from the CDN. The ResourceLoader interface remains unchanged; the provider sits between the manager and the file system.

Resource Analytics Dashboard

Track load times, cache hit rates, memory usage per resource type, and eviction frequency. Surface this data in a developer dashboard. Identify bottlenecks like a 50 MB texture that should be compressed, or a shader that takes 500ms to compile. Use the Observer pattern to collect metrics without modifying loading code.

Hot-Reloading for Development

During development, artists and engineers modify assets on disk and see changes in-game without restarting. A file system watcher detects modifications and calls hotReload(). The system unloads the old resource, reloads from disk, and notifies all active handles. Dependent resources (Materials depending on a modified Texture) are also reloaded using the dependency graph.

Try this problem yourself

Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.


Markdown supported

0%

Editorial Solution

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Resource Hierarchy

ResourceLoader Hierarchy

ResourceHandle as a Generic Wrapper

Design Patterns

Strategy Pattern: Loader Selection

Object Pool / Flyweight: Shared Resource Instances

Proxy Pattern: ResourceHandle

Observer Pattern: Async Load Notifications

Define Class Members (write code)

Enums

Resource (Abstract Base)

Concrete Resources: Texture and Shader

ResourceHandle with Atomic Reference Counting

ResourceLoader Interface and Implementations

ResourceCache with LRU Eviction

ResourceManager (Singleton Orchestrator)

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Resource Loading: The Core Concurrency Challenge

LRU Eviction Respecting Active References

Scaling Beyond a Single Instance

Create/Explain your diagram(s)

Future improvements

Table of Contents

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Resource Hierarchy

ResourceLoader Hierarchy

ResourceHandle as a Generic Wrapper

Design Patterns

Strategy Pattern: Loader Selection

Object Pool / Flyweight: Shared Resource Instances

Proxy Pattern: ResourceHandle

Observer Pattern: Async Load Notifications

Define Class Members (write code)

Enums

Resource (Abstract Base)

Concrete Resources: Texture and Shader

ResourceHandle with Atomic Reference Counting

ResourceLoader Interface and Implementations

ResourceCache with LRU Eviction

ResourceManager (Singleton Orchestrator)

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Resource Loading: The Core Concurrency Challenge

LRU Eviction Respecting Active References

Scaling Beyond a Single Instance

Create/Explain your diagram(s)

Future improvements