,

Database Caching Without Code Changes: Proxies, Redis, and Replicas

Compare proxy caching, Redis, and read replicas by freshness requirements, application compatibility, routing changes, and operational ownership.

Database read request served by a cache hit or routed to the database on a miss, in Cast AI branding

Database caching without code changes uses a proxy to serve eligible repeated SQL reads from memory. Applications connect through a new endpoint, while writes and uncached queries continue to the database. Compare it with application-level Redis caching and read replicas by freshness requirements, query compatibility, routing changes, and operational ownership—not just cache-hit rate.

Which approach fits your read workload?

Key takeaways

  • A proxy can avoid application query-code changes, but deployment, connection settings, and compatibility testing still change.
  • Redis offers application-controlled caching; read replicas execute reads on another database instance.
  • TTL, replication-driven updates, and observed-write invalidation have different consistency requirements.
  • Validate every write path and distinguish measured cache hits from projected opportunity.
  • Fix inefficient queries where possible; caching and query tuning can complement each other.

Choose application caching when the team can own keys, invalidation, and cache-aware logic. Choose replicas for eligible reads that still need database execution. Consider a proxy cache when repeated results can be reused and changing application query code is difficult. The deciding question is whether the approach meets your consistency, compatibility, and recovery requirements.

App-level caching: Redis and the invalidation tax

Redis and Memcached can store application-defined values, not only SQL results. A conventional cache-aside implementation needs client integration, key design, serialization, expiry, and invalidation logic. Performance depends on network placement, value size, and workload; neither is universally the fastest option.

Define which reads consult the cache and how writes update or invalidate related keys. A missed invalidation can expose stale data until expiry or another corrective action. Several services writing the same data need a shared consistency design; a TTL limits lifetime but does not make stale reads acceptable for every operation.

For application-level caching, document the permitted stale-data window and test concurrent reads and writes. Transaction ordering, retries, authorization boundaries, and key design are correctness requirements, not only performance tuning.

Under load, the stampede problem also appears. When a hot key expires, every concurrent request misses at once and they all hit the primary together. The usual fixes are a mutex on the recompute, probabilistic early expiration, or single-flight. Each of those is code you now own.

App-level caching is still the right call in three cases. You need to cache something that is not a SQL result. Your invalidation has to be finer than a row or a table. Or you have the engineers to own it and the write paths are few and well understood. If any of those hold, Redis beats a proxy on control.

Read replicas: read capacity with consistency constraints

A read replica executes queries against replicated data rather than returning a cached result. PostgreSQL streaming replication is asynchronous by default. Synchronous acknowledgement does not automatically mean every replica can serve the latest write: synchronous_commit=remote_apply waits for replay on the selected synchronous standbys. Read routing and transaction snapshots still matter. See PostgreSQL replication.

Measure where replication falls behind: transmission, receipt, or replay. On PostgreSQL, standby queries can conflict with WAL replay and may be canceled. hot_standby_feedback can reduce cleanup conflicts by preventing removal of still-needed row versions, with possible bloat on the primary. It is not a universal lag fix. See Cloud SQL replication guidance.

For MySQL asynchronous replication, examine receiver and applier progress, workload dependencies, large transactions, and table keys. Parallel replication can help eligible workloads, but configuration and transaction dependencies limit how much work runs concurrently.

Use the provider’s documented lag metric together with replication thread status and application-level freshness checks. A single lag number is not proof of read-after-write consistency. The RDS read-replica monitoring guide explains engine-specific interpretation.

A replica adds capacity and operational cost. Aurora supports up to 15 Aurora Replicas for both MySQL-compatible and PostgreSQL-compatible clusters; Billing depends on the deployment and pricing model, including applicable instance and I/O charges. See Aurora cluster architecture.

Replicas are useful for read-only work that can be routed appropriately and meets the required consistency model. They may need cache warmup and cannot accept arbitrary write statements. Route reads that require the latest committed write through a path that provides the necessary guarantee.

Proxy-level caching: no code changes needed, invalidation varies

A database proxy changes the connection path. Compatible applications may need only connection configuration changes, but TLS, authentication, transactions, prepared statements, routing, and failure behavior must be validated. “No code changes” describes the supported integration path; it is not a guarantee for every application.

For example, in Cast AI Database Optimizer, to analyze traffic through the proxy without serving cached results, select Passthrough in the database cache configuration. Responses then come from the database and caching override rules do not apply. This is a proxy mode, distinct from using the read-only Performance Advisor agent alone.

Cast AI database cache configuration with Passthrough selected, alongside Auto and Cache off
Selecting Passthrough in the Cast AI demo illustrates an analysis-only proxy configuration before enabling caching. This is a configuration walkthrough, not a cache-hit or invalidation test.

TTL-based: ProxySQL query cache

MySQL 8.0 removed its old built-in query-result cache. ProxySQL provides a separate query cache selected by query rules and TTLs. This is different from database buffer caches, which cache pages while queries still execute. Check the ProxySQL query-cache documentation for your protocol and release.

ProxySQL’s documented query cache does not invalidate results when writes occur. Results can remain cached until expiry or an explicit flush. Soft TTL permits refresh before hard expiry while other clients may still receive the cached result. Keep freshness-critical reads on a suitable uncached path; configure rules narrowly rather than caching every SELECT.

Prepared-result caching is version- and protocol-specific. ProxySQL documents experimental support for eligible prepared executions in 3.1.12 and 4.0.12. Check supported requests and bypass conditions for the installed build; prepared-statement metadata caching is not the same as caching result rows.

Incremental: Readyset

Readyset uses database replication to maintain results for supported queries. Deployment requires the relevant replication configuration, permissions, connectivity, and an initial synchronization. Managed databases may need parameter changes and provider-specific setup; they are not universally unsupported. Follow the Readyset setup guide.

The architectural distinction is incremental maintenance: upstream data changes update maintained query results instead of waiting only for a TTL to expire. Verify SQL support, parameter behavior, memory requirements, and fallback rules for the workload. Queries that are not supported or not cached still need a database execution path.

Replication-driven updates do not eliminate propagation delay. Validate the consistency contract and observed freshness before relying on cached results. Readyset’s current pricing page describes a source-available Community tier with a 2 GB production RAM allowance and commercial options; check current license terms for the intended deployment.

Cast AI DBO: caching based on observed traffic

Cast AI Database Optimizer combines read-only query and index recommendations with optional proxy caching and connection pooling. The proxy serves eligible repeated reads and uses observed write traffic for Smart Invalidation, without requiring WAL access. The caching documentation describes a first cache hit typically on the second or third occurrence—not a guaranteed hit on the second request.

Auto mode selects caching behavior and TTLs. Per-query or per-table override rules can set a fixed TTL, leave the decision dynamic, or disable caching for that scope. Current documentation clarifies that there is no separate Manual mode; older references describe Auto with overrides. See caching modes and override rules.

Map every writer before enabling a traffic-based cache. A direct SQL session, another service, or a bulk loader may use a different endpoint. Do not assume an unseen write triggers invalidation, a table-level fallback, or automatic cache shutdown. Validate supported routing and freshness behavior; keep unsuitable queries or tables uncached.

The proxy is part of the application’s connection path. Test loss of a replica, planned upgrades, reconnects, and a controlled rollback to the database endpoint. A failed proxy is not inherently a transparent database fallback. Caching and pooling are separate capabilities: Cast AI uses PgDog for PostgreSQL pooling and ProxySQL for MySQL pooling; those engine names do not imply that DBO caching has the same behavior as standalone ProxySQL’s TTL cache.

Compare caching and read-scaling approaches

ApproachBest fitFreshness to validateImplementation work
Application Redis cacheApplication-owned values and custom caching logicKey invalidation, expiry, races, and read-after-write rulesClient integration, keys, write paths, and cache operations
Read replicaEligible read queries needing database executionReplication replay, routing, and snapshot visibilityReplica capacity, read routing, monitoring, and failover
ProxySQL query cacheQueries suitable for rule-based TTL cachingResults may stay cached after writes until expiry or flushProxy deployment, connection settings, scoped rules
ReadysetSupported queries suited to incremental resultsReplication propagation and product consistency behaviorReplication setup, synchronization, SQL compatibility
Cast AI DBO cacheEligible repeated reads through a supported proxy pathObserved writes, routing coverage, TTLs, and overridesProxy setup, connection settings, rules, and workload validation

Use the table to narrow candidates, then test the same representative reads and writes. Deployment time and cost depend on permissions, application compatibility, load, and operating requirements; there is no reliable universal hours-versus-weeks comparison.

What the switch actually changes

Start with a canary client or workload. Record its existing endpoint, authentication, TLS settings, and transaction behavior. Configure the new path, verify access, and exercise representative queries before increasing traffic. Read/write routing may require application support or an additional proxy; changing one connection string cannot safely send writes to a read-only replica.

Budget proxy CPU, memory, connections, and high-availability capacity separately. For replica budgets and rollout checks, see database connection pooling on Kubernetes. Pooling reduces connection churn; caching reduces eligible repeated database work. For PostgreSQL pooling alternatives and constraints, see the connection pooling comparison.

Compare results under a controlled dataset or known transaction sequence, including reads immediately after writes and rollback cases. Differences between two reads of a changing live database do not alone prove stale caching. Test ordering, permissions, tenant isolation, prepared statements, and recovery behavior alongside latency.

What to instrument after you deploy it

Measure both benefit and correctness. Track cache hits, misses, memory, evictions, backend execution time, application latency, and errors over the same workload window. For signal selection, see database observability.

A low hit rate may reflect unique queries, high write frequency, cache warmup, capacity, or deliberate exclusions. Evictions do not automatically mean the cache is undersized. A miss after invalidation can be the expected correct behavior. Add explicit read-after-write tests rather than inferring freshness from cache-hit charts.

Separate observed results from estimates. In Cast AI’s Caches view, hit rate and projected hit rate are different fields; projected database-time savings are not a measured reduction in the cloud bill. Compare equivalent periods and confirm any actual capacity or billing change independently.

When caching is the wrong fix

Caching does not repair an N+1 fetching pattern, missing index, or excessive work on cache misses. Those issues can coexist with a useful cache. Use the N+1 query guide, PostgreSQL slow-query workflow, or MySQL troubleshooting guide to identify avoidable work.

Prefer a query or index change when evidence supports it and you can validate correctness and operational impact. Indexes consume space and add write work; a rewrite must preserve results. Cache suitable repeated reads when reuse provides value under the application’s consistency requirements.

If immediate code changes are unavailable, a carefully scoped cache can provide relief while the underlying issue is addressed. It remains subject to the same compatibility and freshness tests. Record the follow-up work and monitor the uncached path as well as the cache-hit path.

Conclusion

Choose the approach that matches the workload. Redis provides application-level control, replicas add read execution capacity, and proxy caches can reuse results without changing query code on supported paths. Validate routing, consistency, and failure handling before comparing performance. A high hit rate is useful only when the returned results remain correct for the application.

For the wider workflow, read the database optimization guide and the production database optimization techniques. With Cast AI Database Optimizer, you can start with read-only recommendations, review the proposed changes, and enable proxy capabilities where they fit.

Frequently asked questions

Can I cache database queries without changing application code?

A compatible database proxy can cache eligible repeated reads after the application is configured to connect through it. Deployment, TLS, authentication, transactions, and query compatibility still need testing.

Is Redis better than a read replica?

They solve different problems. Redis stores application-managed values; a replica executes reads against replicated database data. Choose by data shape, consistency, routing, and the operational work your team can own.

Can ProxySQL’s query cache return stale results?

Yes. Its documented query cache does not invalidate stored results when writes occur; an entry can remain until its TTL expires or it is flushed. Keep reads requiring immediate freshness on an appropriate uncached path.

Does Cast AI cache every query automatically?

No. Eligible reads depend on caching mode, workload, and rules. Auto makes caching decisions; overrides can set TTL behavior or turn caching off for selected queries or tables. Read-only Performance Advisor alone does not put a cache in the application path.

Are projected cache savings already achieved?

No. Projections estimate opportunity. Validate actual hit rate, database work, application latency, and correctness over representative periods, then measure any separate billing or capacity change.

When should I fix a query instead of adding a cache?

Investigate unnecessary query work, N+1 fetching, and indexing first when practical. Query tuning and caching can work together, but a cache does not correct application fetching or guarantee efficient cache misses.

Cast AI › Blog › Database Caching Without Code Changes: Proxies, Redis, and Replicas