Caching and Data Freshness
One catalog read when product metadata misses
During a spring promotion, Baodium featured a handful of discounted products on its home page. Customers began opening the same product pages, sometimes thousands of times within a few minutes. Each visit asked Catalog Service for descriptions, categories, and image references, which it fetched from PostgreSQL. Most of that information had not changed for days, yet the database was reading the same records again and again.
As traffic increased, the Catalog team’s dashboards began showing longer connection-acquisition times. The situation was familiar from Chapter 1, although this time the problem involved repeated reads rather than a new service dependency. Catalog Service was performing database operations whose results could often have been reused.
One engineer suggested putting Redis in front of those reads. If hundreds of customers requested the same product description within a few seconds, why retrieve it from PostgreSQL for every request? Catalog Service could fetch the description once, store a copy, and reuse it for later visitors.
That sounded reasonable, and the team expected a substantial reduction in database traffic. However, merchants could edit their products while customers were browsing. A cached description might then differ from the database record. The engineers also needed to consider what would happen if Redis became unavailable and thousands of requests suddenly returned to PostgreSQL.
We have already examined how admission limits protect a dependency when too many requests arrive. Caching gives us another option when many requests need the same information. We can avoid some of those dependency calls, provided the application knows when a stored copy is suitable to use.
Repeated Reads and Cache Reuse
The workload made caching an attractive option. One affected Product Page instance handled approximately 1,200 page requests per second under normal traffic. Each page generated three Catalog lookups for product metadata, category information, and image references. That represented about 3,600 source reads per second from that caller before caching. During the promotion, the corresponding demand rose to approximately 4,320 reads per second.
Other Product Page instances contributed their own traffic, which Catalog Service distributed across its instances. The Catalog instances used PostgreSQL connection pools with a maximum of 40 connections each. During busy periods, acquisition delays increased as more reads competed for those connections.
Figure Figure illustrates how repeated requests for the same records reach the source.
Before adding Redis, the engineers examined which records customers requested most often. A small collection of popular products accounted for a large share of the reads. Their descriptions, categories, and image references rarely changed during the day. Once Catalog Service retrieved one of those records, another customer could usually reuse the result.
Consider the expected reduction. If the cache serves 90 percent of the three kinds of lookup in the measured workload, only about 360 of the original 3,600 reads per second need to reach PostgreSQL, before accounting for refreshes and verification. That removes approximately 3,240 database reads per second from the same traffic.
The hit rate needs to be examined by data type. A high hit rate for image references does not tell us how often product descriptions are retrieved from PostgreSQL. The team therefore measured cache reuse and remaining source reads separately for each category.
Caching offers less benefit when most requests retrieve different records, when the values change before anyone reuses them, or when the memory required to retain them exceeds the available budget. Baodium’s promotion had the opposite characteristics, which made it a useful starting point.
The next question was which product information could safely be served from a copy.
Deciding Which Data Can Be Cached
Suppose a merchant corrects a spelling mistake in a product description. A customer who sees the old wording for another minute may experience a minor inconvenience, but the purchase can still proceed correctly.
Now consider an inventory value showing that the product is available when another customer has already reserved the last unit. Or imagine checkout charging a price that differs from the amount the customer agreed to pay.
Those situations have different consequences. The acceptable age of a cached value depends on how the application uses it and what the customer has been promised.
For Baodium, descriptive catalog information could tolerate a documented delay after an update. Inventory reservations and payment decisions had stricter requirements because they changed business state. Checkout continued to consult the services responsible for those decisions.
Table Table shows how the team classified the main product-page values.
The distinction between a browsing price and a purchase price deserves attention. A customer might add an item to the cart while its displayed price is still cached. If the price changes before checkout, the application needs a policy for presenting the new amount and obtaining any required confirmation. Reading the latest database value does not, by itself, establish that the customer agreed to the change.
Product availability also has two meanings. Catalog Service can display an indication that an item is in stock, using data that may be a little old. The actual reservation must be decided by Inventory Service using its authoritative state. Otherwise, two customers could both be promised the last item based on a cached quantity.
Some updates need much faster visibility than ordinary product edits. A merchant might withdraw an unsafe product, or an administrator might revoke access to a protected record. The application cannot assume that the same five-minute freshness policy suitable for descriptive text is suitable for those decisions.
Baodium began by caching browsing metadata. That reduced repeated reads while leaving price confirmation, inventory reservation, and payment authorization with their owning services.
Reading Through a Cache
The Catalog team chose a shared Redis cache. Product Page Service continued calling Catalog Service, while Catalog Service checked Redis before retrieving eligible metadata from PostgreSQL. A value loaded for one request could then be reused by other Catalog Service instances.
Figure Figure shows the read path.
This pattern is called cache-aside. The application first looks for a value in the cache. On a miss, it retrieves the value from the authoritative source and may store a copy for later requests.
The initial implementation was straightforward.
def get_product_metadata(product_id, locale):
key = f"product-metadata:v1:{locale}:{product_id}"
cached = cache.get(key)
if cached is not None:
return decode(cached)
product = catalog_db.fetch_metadata(product_id, locale)
if product is not None:
cache.set(
key,
encode(product),
ttl_seconds=300,
)
return productWhen Redis contains the requested value, the database does not receive another read. On a miss, Catalog Service retrieves the record and gives subsequent requests a chance to reuse it.
This first version is useful for understanding the sequence. It does not yet protect PostgreSQL from many simultaneous misses, and it assumes that the cache is available whenever the application calls it. We will return to the implementation after examining those failure cases.
Choosing Cache Keys
Notice that the key contains the product ID, locale, and a representation version. Each part serves a purpose.
If a customer requests a French description, Catalog Service must not return an English description merely because both requests refer to the same product. A result that depends on currency, region, or another input needs that input represented in its cache identity.
The representation version serves a different purpose. Suppose a deployment changes how product metadata is serialized. A new namespace such as v2 lets the updated code avoid reading entries written in an incompatible format.
That change creates a new operational concern. The new namespace begins empty, so requests that previously reached Redis may temporarily return to PostgreSQL. Changing cache-key formats therefore belongs in the deployment’s capacity planning.
For customer-specific information, the key must identify the appropriate scope, and the application must still verify whether the current caller may access the data. A cached result is not proof of authorization.
Key design also affects invalidation. If a product has several language representations, an edit may require multiple entries to be removed or refreshed. The team needs a reliable way to identify those entries rather than assuming every product has one cached value.
Where the Cached Copy Lives
Redis was a reasonable first choice because Catalog Service ran on multiple instances. A shared cache allowed them to reuse the same entries without maintaining a separate copy in each process.
An in-process cache would avoid the network call to Redis, but each instance would then have its own memory consumption, expiry behavior, and cold-start period. Invalidation would also need to reach every instance that might have loaded the affected entry.
A content delivery network (CDN) was better suited to public product images. When an image URL includes a content hash, an updated image can receive a different URL. The old immutable image can continue to be cached under its original address, while updated product metadata points to the new one. Any requirement to revoke access to old content still needs a separate access or removal policy.
These layers can be combined. However, if a CDN caches a response that Catalog Service has already served from an older copy, the total age seen by the customer may exceed the TTL configured in Redis. Each layer’s caching and validation behavior contributes to the result.
The team began with shared metadata caching and kept the read path relatively simple. Additional local caching could be introduced later if the measurements justified another copy.
Expiration and Data Freshness
Baodium initially used a five-minute time to live (TTL) for ordinary browsing metadata. Once Redis stored a value, the cache could reuse it until the entry expired or was invalidated.
That limit needs careful interpretation. A five-minute TTL measures time since the cache entry was written. It does not necessarily measure how recently the source value was updated or how old the value was when the cache received it.
Imagine a cache loader that reads product version 10 from a database replica. The replica is behind the primary, which has already committed version 11. The loader stores version 10 with a fresh five-minute TTL. Redis now has five minutes remaining on an entry that was already outdated when it arrived.
A loader can introduce a similar delay without replication. It might read a value, pause before writing to Redis, and store the result after another request has updated the source.
For descriptive metadata, the accepted update delay may make those cases tolerable. A stricter freshness requirement calls for more information, such as the source version, the time at which the value was validated, and a limit on how long the loader may continue before its result is rejected.
Shorter TTLs reduce the time an outdated copy can be reused under ordinary expiry, but they also increase database reads. Longer TTLs improve reuse while increasing the potential delay after an update.
The Catalog team needed to compare those effects against the freshness requirement for each kind of data. A TTL chosen only for hit rate could produce a fast page with information that the application was no longer permitted to use.
Updating the Source and Invalidating Cached Data
Now suppose a merchant changes a product description and PostgreSQL commits version 11. Redis may still contain version 10. If a customer requests the product before that entry expires, the application can return the older description.
One approach is to accept that delay. The cache entry expires under its TTL, and the next request retrieves a newer value. This works when the allowed delay includes source-read and replication effects.
Baodium’s merchants wanted catalog edits to appear sooner. The team therefore added invalidation, removing affected cached entries after source changes so that later readers would reload them.
That introduced another failure boundary. PostgreSQL and Redis commit independently. Catalog Service could commit the new description and crash before invalidating its cached copy. The source would be correct while Redis continued serving the old version.
Figure Figure illustrates that gap.
We encountered a similar problem in Chapter 3 when Order Service needed to commit a state transition and publish an event. The transactional outbox gave the application a durable record of the event that still needed to be delivered.
Catalog Service used the same approach for invalidation.
def update_product(product_id, changes):
with db.transaction():
product = product_repo.update_and_increment_version(
product_id=product_id,
changes=changes,
)
outbox.insert(
event_type="ProductUpdated",
aggregate_id=product.id,
payload={
"product_id": product.id,
"source_version": product.version,
},
)The transaction commits the updated product and the obligation to publish its invalidation event together. A separate relay delivers the event, and the cache consumer removes or refreshes the affected representations.
This protects the obligation to invalidate, although readers can still receive an older copy until the event is processed. The TTL provides a fallback if an event is delayed, but the application still needs to measure whether the resulting delay meets its freshness policy.
Every source writer must participate. At Baodium, product records could also change through supplier imports, scheduled promotions, and support tools. Updating only the merchant portal would miss those paths.
A change-data-capture system such as Debezium can read committed database changes and publish them for downstream processing. That provides another option when several applications write to the same tables. It still requires correct event mapping, consumer behavior, and cache-key coverage.
The consumer also needs to know which entries depend on an update. Changing a product category may affect the product detail entry and cached category listings. Removing only the product’s detail key would leave some views displaying the old category.
A Reader That Finishes After an Invalidation
Reliable delivery does not resolve every race.
Consider two requests touching the same product. One is loading metadata after a cache miss, while the other updates the product.
The loader reads product version 10 from PostgreSQL.
A merchant update commits version 11.
The invalidation for version 11 removes the cached copy.
The delayed loader stores version 10 with a new TTL.
The invalidation succeeded, yet Redis contains the older version again. The loader had already retrieved the value before the update and knew nothing about the later commit.
If this matters to the freshness contract, deleting a key is insufficient. The cache needs a way to reject writes whose source version is older than one it already knows has been committed.
Version Watermarks
A version watermark records the minimum acceptable source version for a cached entry. When the invalidation for version 11 arrives, the consumer advances the minimum to 11 and removes any stored value with an older version.
A loader returning version 10 must then be prevented from writing it back. If the cache already contains version 11, a delayed version 10 write must also be rejected.
The version comparison and cache write need to happen atomically. In Redis, a short Lua script can read the stored version and watermark, compare them with the incoming version, and perform the permitted update as one server-side operation.
This avoids a gap between checking the version and writing the entry, where another request could otherwise change the cache.
A delayed invalidation for version 10 also cannot lower the watermark or remove a newer version 11 value. Loaders, refreshers, and warmers must all follow the same write protocol.
There is one more detail. A loader whose version 10 write was rejected should not automatically return version 10 to its caller. If the application’s freshness contract requires at least version 11, that caller needs an acceptable cached value, a bounded source reload, or an unavailable result.
Version watermarks introduce their own lifecycle problem. If eviction, expiry, or a cache restart removes the watermark while an older loader is still running, that loader may write into what appears to be an empty cache.
One possible recovery mechanism uses a cache generation identifier. A loader records the generation before reading the source. After a cache reset, the generation changes, and writes from the earlier generation are rejected. The generation itself must be managed reliably.
This coordination adds complexity and does not guarantee freshness before an update or its authoritative version becomes known to the cache. For browsing descriptions, Baodium could accept a documented delay. Purchase decisions continued using authoritative service checks because their correctness requirements were stricter.
Concurrent Cache Misses
Caching reduces repeated reads only while entries are available. A popular entry can expire at the same moment that hundreds of requests need it.
Imagine a product featured prominently on Baodium’s home page. Its metadata entry expires, and several Product Page requests reach Catalog Service before the first cache miss has been resolved. Every request checks Redis, finds nothing, and attempts to query PostgreSQL.
Figure Figure shows the resulting traffic.
This is called a cache stampede, sometimes described as a thundering herd. The overall hit rate can still look healthy because the burst affects only a small number of keys.
For a popular product, the application can let one caller load the missing value while other callers wait for that same result. This technique is called request coalescing. In Go, the commonly used golang.org/x/sync/singleflight package provides this behavior.
The loader checks Redis again after taking responsibility for the key, since another request may have populated it between the first miss and the start of the load.
Coalescing reduces duplicate queries, although the waiting requests still need deadlines. A canceled customer request should not necessarily cancel a shared database load that other callers still need. The loader requires a bounded lifetime of its own, and the application needs limits on both active loaders and waiting requests.
Coalescing within one process also leaves duplication between instances. Twenty Catalog Service instances may each send one source read for the same key. That may be acceptable when the database can support the small burst.
If a load is particularly expensive, instances can coordinate through a short refresh lease, similar to the recovery leases in Chapter 3. A lease needs an owner, an expiry, and guarded completion. An expired loader may still finish after another instance has taken over, so version checks remain important.
The team would introduce cross-instance coordination only when measurements showed that the duplicate loads justified the additional mechanism.
Spreading Expiration Times
A related problem occurs when many keys are loaded together and receive the same TTL. They may also expire together, sending a burst of unrelated misses to PostgreSQL.
Baodium spread ordinary metadata expiration times across an allowed range using TTL jitter. Rather than giving every key the same expiry, the cache selected a slightly different duration for each one.
The upper bound still had to respect the freshness policy. If a value could be reused for no more than five minutes after caching, jitter could shorten the TTL but could not extend it to six.
Jitter spreads source reads across different keys. Request coalescing remains useful when many callers request the same expired key.
Refreshing Before the Copy Expires
Another option is to begin refreshing while the current copy is still acceptable.
An entry can have a refresh time and a later final expiry. After the refresh time, one loader fetches an updated value while other callers continue using the existing copy. Once the final expiry is reached, the application must obtain an acceptable value or return a permitted degraded result.
This is commonly called stale-while-revalidate. HTTP defines a cache-control extension with the same name, which some CDNs and intermediaries support.
It works well for browsing metadata when the product allows a bounded delay after changes. A failed refresh must not repeatedly extend the final expiry, and background refreshes must use a limited share of the database’s capacity.
Caching Confirmed Absence
Catalog Service also received requests for product IDs that did not exist. A missing product usually required a database lookup, and repeated requests for the same invalid ID could produce the same unnecessary source traffic as repeated requests for a valid product.
The team could cache a confirmed NOT_FOUND result for a short period. This is called negative caching. It needs a representation distinct from an ordinary cache miss.
A database lookup that confirms the product does not exist may justify a negative entry. A database timeout cannot establish that conclusion. If an unavailable database caused Catalog Service to cache NOT_FOUND, a temporary outage could make real products appear nonexistent after the database recovered.
Creating or restoring a product must also invalidate any negative entry for its ID. Otherwise, a newly available product could continue appearing absent until the negative TTL expires.
Negative caching reduces repeated lookups for the same missing ID. Requests containing many different invalid IDs will still create source demand, so the database admission limit must cover those requests too.
What Happens When the Cache Is Empty
The team had reduced the database’s normal read volume, but the next failure test revealed a new dependency.
At a 90 percent cache hit rate, the workload that originally sent 3,600 reads per second to PostgreSQL would normally send only about 360. If Redis restarted with an empty dataset, nearly all 3,600 reads could reach the database again until popular entries were repopulated.
That is approximately ten times the usual source-read demand for the same traffic.
If PostgreSQL had been sized around the ordinary miss rate, sending every request directly to it could cause connection saturation and long response times. Retries from timed-out callers could make the situation worse.
Redis did not have to fail completely. An empty replacement cluster, a namespace change during deployment, or widespread eviction could produce the same miss pattern.
The source needed admission control on every path that could read PostgreSQL, including ordinary cache misses. A limit applied only when Redis returned an error would not protect the database from an empty but otherwise healthy cache.
Protecting the Source Read Path
The original cache-aside example assumed that every miss could immediately query PostgreSQL. The revised path checks the cache under a short deadline, coalesces concurrent misses, and requires a source-read permit before reaching the database.
The helpers in the following snippets are illustrative. The cache result distinguishes a usable value, a confirmed negative entry, an ordinary miss, and an unavailable cache.
def get_metadata(key, request):
cached = cache.try_read(
key,
deadline=request.cache_deadline(),
)
if cached.is_usable:
return cached.result
return singleflight.run(
key=key,
wait_deadline=request.deadline,
loader=lambda context: load_metadata(key, context),
)The first request for a missing key starts a loader. Other requests for that key may share its result, subject to their own deadlines. The loader receives a bounded context managed independently of any one waiting request.
It checks Redis again before acquiring a database permit, because another caller may have populated the entry while the load was being arranged.
def load_metadata(key, context):
cached = cache.try_read(
key,
deadline=context.cache_deadline(),
)
if cached.is_usable:
return cached.result
permit = source_reads.try_acquire()
if permit is None:
return TemporarilyUnavailable("source_read_limit")
with permit:
try:
result = catalog_db.read_metadata(
context.product_id,
context.locale,
deadline=context.source_deadline(),
)
except SourceUnavailable:
return TemporarilyUnavailable("source_unavailable")
stored = cache.try_store_versioned(
key,
result,
deadline=context.cache_deadline(),
)
if stored.rejected_as_old:
return TemporarilyUnavailable("newer_version_required")
return resultThe loader accounts for the source read until the database client has completed its local cleanup. A timeout at the caller cannot automatically release the database resources used by an operation that continues running elsewhere.
The cache population step follows the version rules described earlier. A rejected write means the cache already knows of a newer source version, so this example does not return the older value.
If cache population merely fails because Redis is unavailable, the successfully retrieved authoritative result can still be returned, provided it meets the caller’s freshness requirements. Failure to populate a cache does not invalidate a valid source response.
Confirmed absence uses a separate, short-lived negative entry. Source timeouts and other unavailable results are never stored as NOT_FOUND.
Warmers, background refreshers, and verification reads use the same source allocation. Local limits must also fit within the fleet-wide database budget, including additional instances during deployments and calls that continue after a local timeout.
Warming Without Recreating the Outage
After the cache restart, the engineers warmed a small selection of popular products. Loading the entire catalog would have consumed memory and database capacity for records that might receive no requests.
The warmers used the same database permits as live misses. Their rate could be reduced when customer traffic increased, and their cached entries received spread-out expiration times to avoid another large refresh burst.
The recovery test ran live customer requests and warming together. A cache that fills quickly while the database becomes unavailable to customers has not recovered usefully.
Cache Memory, Evictions, and Hot Keys
A cache can respond quickly and still provide little benefit if entries are evicted before they are reused.
Redis manages memory according to its configured limit and eviction policy. With an all-keys least-recently-used policy such as allkeys-lru, recently accessed entries are favored. A frequency-oriented policy such as allkeys-lfu is designed to favor entries that have been used repeatedly.
Neither choice is automatically best. A large catalog scan might fill an LRU-oriented cache with records requested only once, while an LFU-oriented cache may take longer to adapt when a new promotion makes different products popular.
The team therefore examined hit rate, source-read rate, evictions, and memory usage together. A low hit rate accompanied by frequent evictions could indicate that the cache was too small or storing the wrong kinds of values.
For a self-managed Redis deployment, the configured maxmemory-policy also needs inspection. Under noeviction, writes that require additional memory can fail when the configured memory limit is reached. An eviction policy intended for a cache must be selected and tested against the application’s workload.
The memory estimate includes serialized values, keys, and Redis’s per-entry overhead. Storing complete product responses when callers need only a small subset wastes space and reduces the number of useful entries the cache can retain.
One particularly popular key introduces a different limit. Adding Redis shards does not distribute one key’s reads across all of them. If a single promoted product concentrates traffic on its owning shard, the team may consider a short-lived local cache for that key, provided the freshness policy permits another copy.
That optimization needs its own expiry and invalidation behavior. The team would add it after measuring the hot-key problem rather than assuming every deployment needed another caching layer.
Testing Cache Behavior in Production
The release test needed to establish how much work Redis removed from PostgreSQL and whether the cached values met their intended freshness requirements.
For reads, the engineers tested an empty cache, a slow cache, concurrent requests for one expired product, and many entries expiring together. The database admission limit had to apply regardless of whether Redis returned a miss, timed out, or was unavailable.
For updates, they paused a loader after it retrieved an older product version, committed a newer version, processed the invalidation, and then allowed the loader to finish. That reproduced the race discussed earlier. They also tested delayed invalidations, cache resets during loading, and product creation after a negative entry had been cached.
The production dashboard measured source reads by data class, cache hits and misses, load coalescing, refresh attempts, and rejected source reads. Cache latency, memory usage, and eviction counts were examined per shard, since fleet-wide averages could conceal a problem with one popular key.
The team also sampled cached entries and compared their versions with PostgreSQL. Those verification reads used a limited share of the source budget. A mismatch immediately after an update might still fall within the accepted freshness interval, so the dashboard tracked the age and duration of mismatches as well as their number.
A repair worker could not blindly delete an entry after finding an old version. Another request might have written a newer version between inspection and deletion. Repairs therefore used the same version checks as ordinary invalidation.
Finally, Catalog Service distinguished unavailable metadata from confirmed absence. The product page could omit permitted optional details during a cache incident, but it could not report that a product did not exist merely because PostgreSQL was busy. Checkout continued to obtain authoritative purchase decisions from the services that owned them.
Configuration Caching and Versioned Data
Caching appears in another part of Baodium’s system, although the values involved are smaller than product metadata.
Approximately 500 application instances read feature flags, rate limits, and policy settings from a shared configuration service. Administrators update those settings centrally, while each instance needs a way to use the current configuration without querying the source on every request.
The design becomes easier when configuration contents and the choice of active configuration have different identities.
Suppose an administrator publishes revision 18. The contents of that revision are immutable. An instance can retrieve them by revision number, verify their digest, and reuse the contents without repeatedly asking whether revision 18 has changed.
What can change is the pointer identifying the active revision. When revision 19 becomes active, instances need to discover the change and begin using the newly published contents.
An instance could poll the active-revision pointer once a minute. Under normal operation, that permits a propagation delay approaching one minute, plus scheduling and network delays. A push notification can reduce the delay, but lost notifications and reconnections mean polling or reconciliation is still required.
The notification should identify the new revision. The instance then retrieves and verifies that revision from the authoritative service rather than treating an unauthenticated notification as configuration authority.
Some settings can tolerate this propagation delay. A visual preference or a noncritical feature flag might remain on the previous revision briefly.
A deployment permission that has just been revoked may require a much stricter rule. The enforcement service needs the authoritative current policy before permitting the protected action. If that authority is unavailable, the operation cannot rely on a cached approval whose validity is uncertain.
Table Table separates the main read paths.
For this scale, PostgreSQL can manage publication and the active pointer. A shared Redis layer would need justification from measured configuration traffic. Caching immutable revision bodies locally may already remove most repeated reads.
Chapter 10 returns to configuration and feature flags during deployment, where the timing of a change can determine which requests execute new behavior.
Design Exercise: Profile Caching and Blocking Rules
Consider a professional networking application with 20,000 profile-page requests per second. Each profile shows a name, photograph, job title, and mutual connections.
Most profile information changes only a few times per month, making it an attractive cache candidate. The application also has a blocking feature. When a member blocks another account, the blocked account must lose access to the member’s profile and disappear from the relevant search results within one minute.
How would we use caching without violating that rule?
Selecting the Cached Representations
The name, photo reference, and job title can be cached as profile metadata, using an accepted freshness interval and invalidation after edits.
Mutual connections depend on the viewer as well as the profile owner. A result cached under the profile ID alone could show one viewer information calculated for another. We could compute mutual connections on demand or cache the result briefly under a viewer-profile pair if measurements justified the additional keys.
Blocking changes the read contract. Whether a viewer may access a profile is a decision about the current relationship between two accounts. A cached public profile cannot establish that permission.
One possible design performs a resource-authorization check before returning profile information to an authenticated viewer. The relationship data could use an indexed authoritative store or a dedicated policy service, with capacity established for the expected request rate.
Another design distributes block updates to a versioned access-control cache. That cache needs a refresh or validation mechanism capable of meeting the one-minute requirement even when notifications are delayed or lost.
The search index needs its own handling. Removing a blocked profile from a profile cache does not remove it from search results already stored elsewhere. Search filtering or a verified access check must prevent the blocked viewer from receiving the profile after the allowed interval.
Public, unauthenticated profile views raise an additional product-policy question. If a blocked account can retrieve the same information simply by signing out, the system cannot promise account- specific blocking across that public path without an additional visibility rule. The application must define what blocking means for anonymous access.
Testing a Cold Cache
Now suppose the profile cache restarts at peak traffic and contains no entries.
If every request needs one distinct profile metadata record, the application could generate up to 20,000 metadata source reads per second, before including relationship checks and mutual connection queries.
If many customers request the same profiles, coalescing can reduce the repeated loads. The source admission limit is still necessary because a cold cache can receive a stream of distinct keys that cannot be coalesced.
The recovery plan therefore needs a validated database read budget, bounded loaders, a policy for temporarily unavailable profiles, and warming that gives priority to live requests.
Finally, we would test the blocking rule while the cache is empty, while invalidation events are delayed, and during a cache restart. The one-minute requirement must be verified at the profile and search APIs used by the blocked viewer, rather than inferred from successful event publication alone.
The same application has two caching problems with different consequences. Older profile descriptions may be acceptable for ordinary browsing. Access revocation needs a much tighter decision path.
Summary
Baodium introduced Redis because its catalog was reading the same product information repeatedly. That change removed a large share of the database requests during normal traffic, but the engineers had to decide how long each copy could be used and how updates would reach the cache.
Those decisions became more involved once reads and writes overlapped. An invalidation could finish before an older loader wrote its result. A popular key could expire while many customers requested it. And after a cache restart, PostgreSQL could receive almost ten times its usual source-read demand until the cache was repopulated.
The team addressed those situations through freshness policies, guarded invalidation, request coalescing, and database admission. Purchase decisions continued through their authoritative services, so an older browsing copy could not determine whether checkout was permitted to proceed.
We will encounter similar choices when caching profiles, distributing configuration, or serving public content through a CDN. The application needs to know which copies can be trusted for each operation and how it will behave when a copy is missing.
Baodium’s next problem came from a different part of the deployment. During a Catalog Service release, instances running the same source revision started behaving differently. The engineers had to investigate the runtime environment in which their code was executing. Chapter 6 examines how container images, configuration, and deployment settings affect that result.
After this chapter
⌘/Ctrl K to search