USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Key-Value and Document Stores

Lesson 19/25 | Study Time: 21 Min

Key-value and document stores are popular NoSQL databases designed for high performance and flexible data management.

In backend development, Redis is widely used as a key-value store for caching, session management, and real-time data processing due to its in-memory speed.

MongoDB, a document store, organizes data in JSON-like documents, allowing flexible schemas that can evolve easily as application requirements change.

Key-Value Stores

Key-value stores treat data as simple pairs—a unique key (like a string ID) maps to a value (anything from strings to lists). They're the simplest NoSQL type, optimized for ultra-fast lookups without complex queries.

This design shines in caching and sessions, where you need sub-millisecond access. Let's dive into Redis as the gold standard.

Redis: High-Performance Caching and Beyond

Redis (Remote Dictionary Server) powers giants like Twitter and GitHub for its in-memory speed—data lives in RAM for lightning reads/writes, with optional disk persistence.

Unlike disk-heavy databases, Redis uses an event-driven model for concurrency, handling thousands of operations per second.


Here's why it's a backend staple:


1. Data structures: Beyond plain key-value, it supports strings, hashes (mini-objects), lists, sets, sorted sets, bitmaps, and even geospatial indexes—perfect for leaderboards or real-time analytics.

2. Expiration and eviction: Keys auto-expire (e.g., TTL of 3600 seconds for sessions), with policies like LRU (Least Recently Used) to manage memory.

3. Pub/Sub messaging: Enables real-time features like chat apps.

4. Latest features (Redis 7.4+ as of 2025): Active-Active replication for multi-region setups, Redis Query Engine for JSON querying, and vector search for AI embeddings.


Practical Example: In a FastAPI e-commerce app, cache product details

python
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.setex('product:123', 300, '{"name": "Laptop", "price": 999}') # Expires in 5 min
product = r.get('product:123')


Best Practice: Combine with your relational DB—query Postgres first, cache hits in Redis to cut load by 80%.

Document Stores: Flexible Schemas Unleashed

Document stores hold data as self-contained documents (e.g., JSON or BSON), each with its own schema—no rigid tables required.

This flexibility suits apps with evolving data, like user profiles or logs.

MongoDB leads here, blending SQL-like queries with NoSQL speed. It's disk-based but indexes aggressively for efficiency.

MongoDB: Schema-Free Power for Dynamic Data

MongoDB stores collections of BSON documents, where fields can vary per document—ideal for APIs serving diverse payloads.

Its aggregation pipeline mimics SQL GROUP BY but handles arrays and nested objects natively. Key perks include horizontal scaling via sharding and multi-document ACID transactions (since v4.0).


1. Schema flexibility: Add fields on-the-fly; no migrations needed.

2. Indexing: Compound, text, geospatial—full-text search rivals Elasticsearch.

3. Drivers and integration: Official Python driver (PyMongo 4.8+ in 2025) supports async with motor for FastAPI.

4. Recent advancements: Atlas Vector Search (2025 updates) for semantic search, and Time Series collections for IoT/metrics.


Hands-on Example: Storing blog posts in a Django backend:


1. Connect: from pymongo import MongoClient; client = MongoClient('mongodb://localhost:27017/'); db = client['blogdb']

2. Insert: db.posts.insert_one({"title": "Redis Caching", "tags": ["nosql", "backend"], "views": 150, "author": {"name": "Alex", "verified": True}})

3. Query: db.posts.find({"tags": "nosql"}, {"title": 1, "views": 1}).sort("views", -1)

Pro Tip: Enforce schemas lightly with JSON Schema validation to catch errors early.

Redis and MongoDB in Tandem: Real-World Strategies

Few apps use one alone—combine them for a hybrid stack. Redis fronts MongoDB for hot data, slashing latency.

Consider a social media backend: MongoDB holds user profiles (flexible fields like bio, posts); Redis caches feeds and sessions.

Implementation Steps


Performance Tuning and Best Practices

To maximize these stores, tune for your workload—80% reads? Prioritize Redis. Write-heavy? Shard MongoDB.

Common pitfalls: Redis OOM (out-of-memory) from unchecked growth; MongoDB slow scans without indexes.


Tuning Checklist


1. Redis: maxmemory-policy allkeys-lru; use pipelines for batch ops.

2. MongoDB: Compound indexes on frequent filters; limit() for pagination.

3. Python integration: Async clients (aioredis, motor) for high concurrency.

4. Monitoring tools: Prometheus exporter for Redis; MongoDB Ops Manager.


In benchmarks (DB-Engines 2025), Redis tops key-value at 1M+ ops/sec; MongoDB leads documents with 100k+ queries/sec on modest hardware.

Sales Campaign

Sales Campaign

We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.