Skip to main content
Insyrge - Zoho CRM & Business Automation Consulting
← Back to All ArticlesAI & Business Automation

Redis Caching in Front of PostgreSQL

How to add Redis caching to a PostgreSQL application: what to cache, how to keep data fresh and what happens when memory runs out.

•Manav Sharma
Redis Caching in Front of PostgreSQL

Add Redis caching in front of PostgreSQL with care: fix slow queries first, choose lazy loading or write-through, set TTLs, pick an eviction policy.

When a PostgreSQL-backed application slows down under load, adding a cache is a tempting fix. Store the results of expensive or frequent queries in memory, serve repeat requests from there and let the database rest. Redis caching is a common way to do this, and it can work well. It also adds a second copy of your data that can go stale, a new service that can fail and a set of decisions about what to cache and for how long. This guide explains when Redis caching in front of PostgreSQL is worth it, the main strategies for keeping data fresh, how expiry and eviction work and what to monitor.

Fix slow queries before caching them

A cache hides slow queries rather than fixing them. Before adding one, find out why the database is slow. PostgreSQL devises a query plan for each query, and its documentation explains how to read those plans with EXPLAIN and EXPLAIN ANALYZE (PostgreSQL: Using EXPLAIN). A missing index, a query that fetches far more rows than it needs or a loop that sends one query per record can often be fixed directly, with no cache needed.

Connection limits and read load are other common causes. Our guide to PostgreSQL read replicas covers moving read traffic to standby servers, and pooling connections often helps too. Reach for a cache when the remaining load is repeated reads of data that does not change on every request.

What to cache

Good candidates share a few traits:

  • Read much more often than they change
  • Expensive to compute or query, such as aggregates, reports or results that join many tables
  • Acceptable if slightly out of date for a short period
  • Safe to recompute if the cached copy disappears

Examples include product catalogues, configuration and reference data, dashboard summaries and responses from slow external APIs. Poor candidates include account balances, stock levels used for ordering, permissions and anything where a stale value could cause a wrong decision or a security problem.

Redis caching strategies

AWS documentation on ElastiCache caching strategies describes two common approaches and their trade-offs (AWS: Caching strategies). The page is written for Memcached, but the strategies apply to Redis in the same way.

Lazy loading loads data into the cache only when it is requested. The application checks the cache first; on a miss, it queries the database, stores the result and returns it. Only requested data is cached, but the first request for each item is slower, and the documentation notes that data written to the cache only on a miss can become stale, because nothing updates it when the database changes.

Write-through updates the cache whenever data is written to the database. The documentation lists the advantage that cached data is never stale, and disadvantages including missing data when a new cache node starts, until that data is next written, and cache churn, because most data written is never read. It suggests combining write-through with lazy loading and adding a time to live (TTL) to limit wasted space.

Set expiry deliberately

The Redis documentation for the EXPIRE command explains that after a key's timeout expires, the key is deleted automatically, and that a key with a timeout is called volatile in Redis terminology (Redis: EXPIRE). TTLs act as a safety net: even if an update is missed, stale data disappears eventually.

Choose each TTL from the business tolerance for staleness, not from a single global default. A product description might be fine for an hour; a dashboard total might need a minute. Where data changes through your own application, delete or update the cached key when the change is written, and keep the TTL as a backstop.

Plan for memory limits and eviction

Redis keeps data in memory, so it will run out eventually. The Redis documentation on eviction explains that the maxmemory directive sets the maximum memory for cache data and that an eviction policy decides what happens when that limit is reached (Redis: Key eviction). Policies include noeviction, under which keys are not evicted and the server returns an error for commands that would cache new data, policies that evict the least recently or least frequently used keys across all keys, and volatile policies that only evict keys with a TTL.

For a pure cache, a policy that evicts across all keys usually fits, because any key can be recomputed. If the same Redis instance also holds data that must not be lost, such as job queues or sessions, either use a separate instance or choose a policy and TTL scheme that protects that data. Mixing cache and durable data in one instance with the wrong policy can lead to important data being evicted.

Worked example: a hypothetical caching plan

The table below is a hypothetical plan for a B2B ordering portal. It shows how to decide strategy and TTL per data type, not tested settings.

DataChangesStaleness toleranceStrategyTTLProduct catalogueDailyMinutesLazy loading, delete key on product updateHoursPrice lists per customerWeeklyLow; wrong price is costlyWrite-through on price change, plus lazy loadingShortDashboard summaryConstantlyA minute or twoLazy loadingShortStock level for orderingConstantlyNoneDo not cache; read from databaseNoneUser permissionsRarelyNoneDo not cache, or invalidate on every changeNone

Handle cache failures gracefully

The application should keep working, more slowly, if Redis is unavailable. Wrap cache calls so that errors fall back to the database rather than failing the request, and set short timeouts on cache operations. Be careful of the moment a popular key expires: if many requests miss at once, they can all hit the database together. Techniques such as letting one request rebuild the value while others wait, or refreshing popular keys shortly before they expire, reduce that risk.

Monitor the cache

Track the hit rate, memory use, evictions, latency and errors. A low hit rate means the cache is not helping and may be caching the wrong things. Rising evictions mean memory is too small for the working set. Watch database load and response times before and after the change, so you know whether the cache delivered what you expected. Our guide to API response time explains how to measure endpoint performance end to end.

Frequently Asked Questions

When should I add Redis caching to a PostgreSQL app?

After fixing slow queries and connection issues, when the remaining load is repeated reads of data that changes less often than it is read and can be slightly stale.

What is the difference between lazy loading and write-through?

Lazy loading fills the cache on a miss, so data can become stale. Write-through updates the cache on every database write, so cached data is current but much of it may never be read.

What happens when Redis runs out of memory?

It depends on the eviction policy. Under noeviction, commands that would add data return errors; other policies remove keys, such as the least recently used ones.

Should I cache user permissions?

Generally no, unless you invalidate the cache on every change. A stale permission can let someone see or do something they should not.

Speed up applications without stale surprises

We review database performance, design caching strategies and set up monitoring for PostgreSQL applications. See our custom app development services, or talk to us about Redis caching.

About the Author

Manav Sharma is the founder of Insyrge and a CRM solutions architect. He works across Zoho, Salesforce, HubSpot, Odoo and more, designing the CRM setups, integrations and automations that keep sales and operations teams working from the same data.

Need Help Implementing This in Your Business?

Our certified Zoho consultants and automation experts can help you design and deploy custom workflows tailored to your operations.

Book Free Consultation