Writing
Database Performance and Caching: Faster Reads Without Rewriting Your App
How auto-caching and SQL analytics helped a media publishing platform cut its database bill, and the options for faster database reads today, with the cache invalidation tradeoffs each one brings.
By Ka Lun Chan · Architecture / Web development
How do you make a database-backed site faster without rewriting it?
Find the queries that cost the most time, then cache the reads that repeat. Pick the caching layer by how much application code you can change and how stale each piece of data is allowed to be. A transparent caching proxy needs no code changes; application caching gives you the most control over freshness.
I first wrote about this on my old blog, across three short posts about a tool that helped my team. This version keeps that story and my opinions, and updates the tools and the search guidance, which have both moved on.
My view hasn’t changed. Performance has to be a focus up front, before the ceiling starts falling in. When it does need fixing, caching is often the first step, and the best caching is the kind that doesn’t involve your application at all.
What happened when database performance hurt our publishing platform?
At a media publishing platform, slow pages showed up as business numbers: revenue, organic traffic and session time dipped, and the database bill was the biggest line in our infrastructure costs. Auto-caching and SQL analytics from Heimdall Data helped us find the bottlenecks quickly and cut that cost.
Most teams don’t worry about performance until those numbers move or until infrastructure cost shows up on the P&L. That was the trigger for us too. Amazon RDS was the most expensive item in our infrastructure.
Heimdall Data’s auto-caching came to our rescue. We didn’t have to write extra code or decide what to cache and when to expire it, which shortened our time to market. Its analytics showed us the slow SQL quickly, so we spent less time hunting for bottlenecks and fixing them. We cached more, fixed what the analytics pointed at, and reduced our database cost. We watched SEO ranking, user session time and the number of pages search engines crawled per day improve day after day.
That platform is also where I led a re-platform of our titles from WordPress to Ruby on Rails on AWS. I’ve written about the cost side of those decisions in how infrastructure costs changed from carrier networks to the cloud.
Is Heimdall Data still around?
Yes. When I checked for this refresh, Heimdall Data’s site still sold its Database Proxy, alongside a Database PAM product for privileged access, with buy and free-trial options. I found no announcement that it had been acquired.
The Database Proxy page describes the same ideas we used: an auto-expiring cache for frequent queries, read and write splitting to replicas without application changes, and SQL analytics with query monitoring and tuning recommendations. It mentions auto-expiry logic and invalidation rules but doesn’t explain how they work, so I’d test that against your own write patterns before trusting it with data that changes often.
How do you find which queries are slowing you down?
Rank queries by total time spent, not by the slowest single run. In PostgreSQL that’s pg_stat_statements. On Amazon RDS, the dashboard formerly called Performance Insights is now CloudWatch Database Insights.
A query that takes 20 milliseconds but runs on every page view usually costs more than a 2 second report someone runs once a day. pg_stat_statements tracks calls and execution time per normalized query:
-- postgresql.conf (restart required):
-- shared_preload_libraries = 'pg_stat_statements'
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
-- The queries that cost the most time in total
SELECT query, calls, total_exec_time, mean_exec_time
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;On RDS, AWS ended Performance Insights on July 31 and moved its users to CloudWatch Database Insights. Standard mode keeps seven days of per-query metrics free and charges for longer retention. Advanced mode adds per-query statistics, slow-query analysis and execution plans for some engines. If you used Performance Insights and didn’t choose a mode, check which one you’re on.
Once you have the list, fixing the queries themselves is a separate job. I cover that in how to find and fix slow SQL queries. Caching is for the reads that are already reasonable but happen far too often.
What are the options for taking read load off a database?
They range from proxies that need no code changes to caches your application controls. The more control you take, the more code and review it costs, and the more precisely you can decide when data goes stale.
| Option | What it does | The catch | App changes |
|---|---|---|---|
| Transparent caching proxy | Sits between app and database, caches repeated query results and reports on SQL | Another hop to run and secure. You have to trust its invalidation rules. | None |
| ProxySQL query cache | Caches result sets for queries matched by a rule, for a set time | Writes don’t invalidate entries, so reads can be stale until the TTL ends | None |
| RDS Proxy | Pools and reuses connections, rides through failover | No result caching. Every query still reaches the database. | None |
| Read replicas | Spread reads across copies of the database | Replication lag, and you pay for each replica | Route reads |
| ElastiCache (Valkey, Redis OSS, Memcached) | In-memory store your code reads before the database | Your code decides what to cache and when it expires | Yes |
| App cache (Rails.cache) | Caches computed results, fragments or pages in the framework | Key design and expiry live in your code and reviews | Yes |
The common mix-up is RDS Proxy. Its documentation describes connection pooling, failover handling and IAM authentication. It helps when connection storms are the problem, but it doesn’t cache results, so it won’t reduce the work each query does.
ProxySQL’s query cache is the closest open source equivalent to what we had: rules match query patterns and set a lifetime in milliseconds, for MySQL and PostgreSQL.
-- ProxySQL admin: cache matching article reads for 60 seconds
INSERT INTO mysql_query_rules (rule_id, active, match_digest, cache_ttl, apply)
VALUES (10, 1, '^SELECT .* FROM articles WHERE', 60000, 1);
LOAD MYSQL QUERY RULES TO RUNTIME;
SAVE MYSQL QUERY RULES TO DISK;For application caching on AWS, Amazon ElastiCache runs Valkey, Memcached or Redis OSS, either serverless or as clusters you size. In Rails, Rails.cache sits on top of whichever store you configure. New apps default to Solid Cache, which stores entries in a database, and Redis remains a built-in option.
How do you keep cached data from going stale?
You choose which staleness you can live with. A time limit bounds how old data gets, updating the cache on writes keeps it current at the cost of extra writes, and versioned keys retire entries when a record changes. Most systems use a mix.
AWS’s caching strategies guide lays out the tradeoffs well. Lazy loading caches only what gets requested, but every miss costs extra trips and data can go stale. Write-through keeps the cache current but fills it with data nobody reads. A TTL on top of either keeps the damage bounded without guaranteeing freshness.
Transparent caches carry the same tradeoff with less visibility. ProxySQL states plainly that writes don’t invalidate stored results, so a reader who has just saved something can see the old version until the TTL ends. Its advice is to keep reads that must reflect a write on an uncached path. For a publishing site that was fine for article pages and wrong for an editor’s preview.
In Rails, versioned keys handle the record itself, and a TTL catches what the key can’t see:
class Article < ApplicationRecord
# The key includes updated_at, so editing the article retires the old entry.
# Other articles publishing won't change this key, so the TTL covers that.
def related_articles
Rails.cache.fetch([cache_key_with_version, "related"], expires_in: 1.hour) do
Article.published.where(topic_id: topic_id).where.not(id: id).limit(5).to_a
end
end
endThe practical rule I use is to write down, per kind of data, how stale it may be. Article bodies can be minutes old. Prices, permissions and anything a user just edited usually can’t.
Does database speed still matter for search ranking?
It matters through page experience. Google now measures Core Web Vitals, and a slow database delays the server response that every page load waits on. Relevance still comes first, so speed helps most when your content already competes.
When I first wrote this, Google had just announced that page speed would become a ranking factor for mobile searches, and its announcement said it would affect only the slowest pages. The guidance has changed since. Google’s Core Web Vitals documentation sets targets of Largest Contentful Paint within 2.5 seconds, Interaction to Next Paint under 200 milliseconds and Cumulative Layout Shift under 0.1, and says good scores align with what its ranking systems reward.
The page experience page is also clear that good scores don’t guarantee top rankings and that Google shows the most relevant content even when its page experience is weak. Database time shows up mainly in how quickly the server sends the first byte, which pushes back everything after it, including the largest paint. I wrote more about what moves traffic for publishers in digital publishing, SEO and AI search.
Sources
Checked in November against Heimdall Data’s site, the ProxySQL, PostgreSQL, Rails and AWS documentation, and Google Search Central. The story is from my original posts; the table and recommendations are mine.
- Heimdall Data: home page
- Heimdall Data: Database Proxy
- ProxySQL Docs: Query Cache
- Amazon RDS User Guide: Amazon RDS Proxy
- Amazon CloudWatch User Guide: CloudWatch Database Insights
- PostgreSQL Docs: pg_stat_statements
- Amazon ElastiCache User Guide: What is Amazon ElastiCache?
- Amazon ElastiCache User Guide: Caching strategies
- Ruby on Rails Guides: Caching with Rails
- Google Search Central: Using page speed in mobile search ranking
- Google Search Central: Understanding Core Web Vitals and Google search results
- Google Search Central: Understanding page experience in Google Search results
Short answers
What is the fastest way to reduce database load without changing application code?
A transparent caching proxy, such as Heimdall Data’s Database Proxy or ProxySQL’s query cache, can serve repeated query results without code changes. Find the most expensive queries first, and check how the proxy handles writes, because ProxySQL’s cache expires entries only by time.
Does Amazon RDS Proxy cache query results?
No. RDS Proxy pools and reuses database connections, handles failover and supports IAM authentication. Every query still runs on the database, so for caching you need ElastiCache, an application cache or a caching proxy.
What replaced RDS Performance Insights?
AWS ended Performance Insights and migrated its users to CloudWatch Database Insights. Standard mode includes seven days of per-query metrics at no extra cost, and Advanced mode adds per-query statistics, slow-query analysis and longer retention.
Does database speed affect SEO?
Indirectly. Google measures page experience through Core Web Vitals, and a slow database delays the server response every page waits on. Google still ranks the most relevant content first, so speed helps most when your content already competes.
Measure before you cache
Turn on query statistics this week and look at the top ten by total time. That list tells you whether you need a fix, a cache or a bigger instance, and it’s usually not the last one.