Materialized Views Use Cases with Key-Value Storage
Learn how to use key-value storage to cache materialized views and improve your database read performance.
Relational databases (Postgres, MySQL) are great at "truth". They ensure data is consistent and normalized.
But they are terrible at "speed" when you have complex joins. Querying a dashboard might involve joining users, orders, items, and payments. This kills performance.
The solution? Materialized Views with Key-Value Storage.
What is a Materialized View?
In SQL, a "view" is a saved query. A "materialized view" is the result of that query saved to disk. In the modern web stack, we take this a step further. We compute the result and push it to a fast Key-Value store.
The Pattern
- Write Path: User places an order -> Writes to Postgres (source of truth).
- Async Job: A worker listens to the database (CDC or event bus).
- Compute: The worker recalculates the "User Dashboard" JSON blob.
- Cache Path: Worker writes the JSON blob to Key-Value store (
SET user:123:dashboard '{...}').
Why Key-Value is Perfect Here
- Read Speed: When the user loads their dashboard, you do a single
GET user:123:dashboard. 1ms later, you have the data. No SQL joins, no CPU load on the primary DB. - Atomic Updates: You replace the whole view at once. The user never sees a "half-loaded" state.
- Cost: Hosting these views in a KV store is cheaper than scaling a vertical Postgres instance to handle read traffic.
Implementation Example
// Background Worker
async function updateUserView(userId) {
const [user, orders] = await Promise.all([
db.users.findById(userId),
db.orders.find({ userId })
]);
const dashboardData = {
name: user.name,
totalSpent: orders.reduce((sum, o) => sum + o.total, 0),
recentOrders: orders.slice(0, 5)
};
// Persist to BaseKV
await redis.set(`view:user:${userId}`, JSON.stringify(dashboardData));
}
// API Endpoint
app.get('/dashboard', async (req, res) => {
// Instant fetch
const data = await redis.get(`view:user:${req.user.id}`);
res.json(JSON.parse(data));
});
Conclusion
Don't make your database do the same hard work every time a user refreshes the page. Compute once, cache forever (until it changes). Using a Key-Value store for materialized views is the secret weapon of high-scale applications.
BaseKV is the perfect persistent home for your views. Try it now.