Skip to content

Instantly share code, notes, and snippets.

@monotykamary
Created April 14, 2026 06:32
Show Gist options
  • Select an option

  • Save monotykamary/95fe7ad70f75c6d0b256a99b22f3e4b0 to your computer and use it in GitHub Desktop.

Select an option

Save monotykamary/95fe7ad70f75c6d0b256a99b22f3e4b0 to your computer and use it in GitHub Desktop.

Thread-Safe LRU Cache with TTL

Implement an in-memory LRUCache class in Ruby. It must support O(1) get and put operations. You need to handle production realities:

Requirements:

  1. get(key) → Returns value or nil if key doesn't exist or is expired.
  2. put(key, value, ttl_seconds) → Inserts/updates. Evicts least recently used if capacity exceeded. TTL is per-key expiration.
  3. Thread-safe: Multiple threads can safely call get/put concurrently.
  4. Expiration happens lazily (on access) or proactively (bonus points).

Example:

cache = LRUCache.new(2) # capacity 2
cache.put("user_1", {name: "Duy"}, 1) # 1 second TTL
sleep(2)
cache.get("user_1") # => nil (expired)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment