Design an Event-Based In-Memory Storage System

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-09-13

Problem Statement

Design an in-memory storage system that supports real-time event-driven updates. The system should allow clients to store, retrieve, and subscribe to changes on keys or data objects. It should support concurrent access, event notifications, and optional persistence.


Functional Requirements (FR)

Data Storage

•Store key-value pairs in memory.
•Support data types like strings, numbers, lists, or maps.
•Retrieve values by key efficiently.


Event Subscription

•Allow clients to subscribe to events on keys (create, update, delete).
•Trigger callbacks or notifications when events occur.
•Support multiple subscribers per key.


CRUD Operations

•set(key, value) – add or update a key.
•get(key) – retrieve a key’s value.
•delete(key) – remove a key.
•update(key, value) – update a key with new value.


Concurrency & Thread-Safety

•Handle multiple clients reading/writing simultaneously.
•Ensure consistent state and correct event notifications.


Optional Features

•Expiration / TTL for keys.
•Persistence to disk or snapshotting for recovery.
•Support for batch operations.
•Event filtering (subscribe only to certain event types).


Suggested Classes & Responsibilities


Class: InMemoryStore


•Attributes: store (HashMap), lock (for concurrency).
•Methods:
•set(key, value)
•get(key)
•delete(key)
•update(key, value)
•registerSubscriber(key, subscriber)


Class: Subscriber


•Attributes: id, callback
•Methods: notify(event)


Class: Event


•Attributes: key, type (CREATE, UPDATE, DELETE), oldValue, newValue, timestamp
1.Class: EventDispatcher
•Attributes: subscriberMap (key → list of subscribers)
•Methods:
•dispatch(event) – notifies all subscribers for a key.
2.Class: TTLManager (Optional)
•Attributes: expiryMap (key → expiryTime)
•Methods: evictExpiredKeys() – runs periodically to remove expired keys.


Data Flow (High-Level)


1.Client performs set(key, value) → InMemoryStore updates the store.
2.EventDispatcher generates a CREATE/UPDATE event.
3.Event dispatched to all registered subscribers for the key.
4.Subscribers receive the event and execute their callback.
5.Optional: TTLManager evicts expired keys and triggers DELETE events.


Key Design Considerations


•Thread-Safety: Use locks or concurrent data structures to prevent race conditions.
•Event Ordering: Ensure events are delivered in the correct order for each key.
•Performance: Minimize latency in event notification while maintaining high throughput.
•Memory Management: Handle large number of keys efficiently; implement eviction policies.
•Extensibility: Support future features like persistence, batch operations, and filtered subscriptions.


Solution

Comments