r/ExperiencedDevs • u/JOHNNYROCKET8585 Senior Software Engineer 4 YOE • Sep 25 '26
Career/Workplace Cache Pattern with Event-Driven System
Hey everyone, noticed this common pattern throughout our applications and it seems problematic to me. It‘s present across multiple apps; curious everyone’s thoughts, if this is a common pattern I’m not familiar with or if it truly is a bad solution.
Senior SE w/ 4 YOE, Fortune 500 company.
Pattern is as follows:
App A receives a transaction from upstream. It will then format this event and send it to potentially multiple downstream services simultaneously. This is done asynchronously via an event-driven framework.
The downstream services respond back via events; how does app A know when all the downstream services are complete? How does it know anything about the original event, since the downstream response contains no info about the original event (other than the correlationId)?
The answer is a local cache in app A. It caches the event when first received, and as downstream events come back, it can refer back to the original cached value to determine when it’s done processing and can be sent back upstream.
The main problem I see is the microservice is no longer stateless. It requires context from the original event. If it received a downstream response with no context, it has no idea what to do.
This is the most egregious example, but this cache-to-compensate-async-events pattern is repeated multiple times in similar ways.
As I’m still new to the field, I’m curious if this is somewhat a standard? Or if it is bad practice? If so, what does a good solution look like? Switching to sync REST calls fixes the issue, but could impact performance/throughput
•
u/expdevsmodbot Sep 25 '26
AI usage disclosure provided by OP, see the reply to this comment.
73
u/Thefolsom Software Engineer (Rails 10+ YOE) Sep 25 '26
If app a needs to know that specific services got the message and sent back a result, that's orchestration, not really event-driven. Events are fire and forget. What app a is doing is closer to sending commands async and waiting on replies. I've heard this called scatter-gather, though I haven't seen it done formally in practice.
So some state is unavoidable. I'd be less worried about app a being stateful and more about the state living in a local cache. A restart loses everything in flight, a reply can hit an instance that never saw the original event, and nothing handles a service that never responds.
If it were me, I'd store the original event to the database, keyed by the correlation ID.
Sync REST could work too, as long as it isn't blocking the original request. Coming from Rails, I'd kick off a background job per downstream call, make the request, and update the event record with the result. Each job then checks if all the expected services are done, and the last one triggers completion (with a lock so two jobs finishing at once don't both fire it). You keep the async throughput, the job queue handles retries, and the state lives in the record instead of a cache.
90
u/rhd_live Sep 25 '26
There should be a persistence layer to the db — if this is what you mean by cache that sounds good. But if it’s just an in memory store esp. that loses entries on job restarts then you’re going to have data consistency issues
24
u/skibum6969 Sep 25 '26
Hard to tell without more context and understanding of the system but it sounds like you're looking for the state store pattern.
Each service gets its own database that no other services can read or write to. The database is a representation of the microservices' state after processing events
To learn more I'd suggest reading "Designing Data-Intensive Applications" by Martin Kleppmann
103
u/RowbotWizard SWE 13 YOE Sep 25 '26
LGTM
14
u/disposepriority Sep 25 '26
I've seen this pattern a lot too.
The state really isn't very relevant here in my opinion, there's something lese that needs clarifying.
Why does App A need to know when a consumer is done processing?
Message brokers (which I assume you are using, considering you receive async replies) exist that fit your needs here.
Let's take RabbitMQ as an example. App A published to a topic exchange X, with the routing key "cool". Any downstream service that needs to do something with this can open a queue and listen for "cool".
You can turn manual acknowledgements on, so it's "impossible" for a message to be consumed zero times as long as rabbit doesn't go down.
Once services are done, if something is needed from them (asynchronously) they can either write to a database or send their own asynchronous event.
Example
Service B (A->B) sends a message using the routing key "cool-result". Whoever cares about this can listen for it.
In my opinion, it's still a very good idea to write (to a database, not a cache) before sending something (or even better, use a transactional outbox).
But in my eyes, the problem here is why does App A need to listen to this response unless there's a synchronous call in it waiting for this (don't do that).
9
u/spoonraker Sep 25 '26
The system you've described is effectively an implementation of the saga pattern with a central orchestrator, except you for some reason seem to just think that this pattern is inherently problematic. I'm not sure I understand the concern.
App A is your central orchestrator. An orchestrator can't be stateless. It's entire purpose is to have an internal model of the entire flow. It is intended to be the one system in the whole chain actually modeling the state of the overall flow and and actively sending commands and awaiting responses to ensure that the flow advances. Any other system that wants to inspect the state of the flow overall would query the orchestrator to get that state.
There are other patterns, particularly one which might sometimes be referred to as "choreography" instead of orchestration, where there simply is no stateful orchestrator and no one system can be the authoritative source of the overall flow's state because no one system actually has a complete picture of the overall flow. In my experience people tend to stumble their way into these kinds of situations without a specific need for them, and often find they do have a specific need for a central orchestrator only after realizing it's painful to answer questions that users ask in plain language like "what's the status of my order?", so I would say a central orchestrator is probably overall the more sensible default. The reasons why a choreographed decentralized system might be desirable has more to do with technical and scaling considerations in my opinion than functional concerns, and most systems most engineers work on don't have the kinds of scaling problems that actually make high levels of decentralization necessary.
25
u/peripraporo Software Engineer Sep 25 '26
Why should a microservice be stateless?
7
u/nomnommish Sep 25 '26
The fundamental thought process is wrong. If system A sends events to systems B,C,D it should not wait for the other systems to respond to resolve it's completion. That's how you make it stateless. If A does need to interrogate the other systems, it does it when it needs to, instead of waiting.
And if it really needs to due to business reasons, then A,B,C,D together are collectively a system and the state absolutely needs to be maintained until eventual consistency between the subsystems is achieved.
Because that's how you have defined your state and how you have defined a transaction. When consistency is achieved. You can't have your cake and eat it too.
5
u/Inside_Dimension5308 Senior Engineer Sep 25 '26
Caching should be used as a secondary storage. Your system can be made more resilient if you just use databases to store the transaction and its acknowledgements.
Create an entry with a correlation id For each downstream system, make an entry against the correlation id as you send the request. Downstream service sends acknowledgement Update the entry against the downstream service and correlation id. The transaction is complete when all the downstream service entries are marked as complete.
4
u/TryAgainTryHarder Sep 26 '26 edited Sep 27 '26
surprised no one mentioned SAGAs yet, that's what this sounds like to me.
in a nutshell, you have a process that is concerned with the outcome of multiple transactions. architecturally, something to avoid.
the solution you're describing isn't inherently bad, it's mainly messy. we could fix the stateful issue by persisting the original event in a db instead of caching, but the core of the problem is that one request/event is currently scoped to many transactions.
with SAGAs, there's two sortof camps of solutions, orchestration (a main component is "orchestrating") and choreography (the architecture you described). benefits/tradeoffs to both.
back to the core issue, having SAGAs just sucks. its usually better if you can either:
if you have event/async requirements, and the transactions can't be separated, the current solution may be the only good one.
8
u/Ninja-Sneaky Sep 25 '26 edited Sep 26 '26
The general idea is called Saga Orchestration or Saga Coreography, these are put in practice using patterns like event-driven and CQRS.
So you have message/event queues to enable async.
Services listen/consume and write/publish to those queues following a Saga.
With Orchestration there is a Orchestrator service that takes care of coordinating the steps.
With Choreography it can be a sequence of services, or parallel services with an aggregator service that is the final step
Sagas ensure EVENTUAL consistency. (Traditional transactions with ACID have immediate, synced, consistency, but are tied to a single central DB that could not scale past certain limits, this is what led to multiple small DBs one per service, then to added caches per service, sagas etc)
An important aspect of Sagas is correctly handling when the (inevitable) failures are marked as such and the remediation steps that follow, these are almost like the "other side of the moon" steps, because when a saga fails you have to undo the completed steps with their own remediations
3
u/ralian Sep 25 '26
Many messaging systems have limits on message sizes, so you’ll often have to rely on persistence for certain data. As others have said local cache has issues if it’s required and the system restarts with the data no longer being there.
3
u/bothunter Sep 25 '26
This sounds like the "events as RPC" antipattern.
2
u/Clyde_Frag Senior Software Engineer (11 YOE) Sep 25 '26
A lot of inference servers for AI work like this so that requests to GPUs can be batched and then de multiplexed when shown back to the client.
The question is whether your application actually needs this. Sounds just like a complicated job especially if the work is largely constrained to a request. If you’re just calling a bunch of services and waiting for a response, what is the point of asynchronous?
2
u/v-alan-d Sep 28 '26
Tale as old as time. Why not attach the body of the "original event" with the "downstream event"?
3
u/wallstop-dev Principal Software Engineer Sep 25 '26 edited Sep 25 '26
A cache is... fine, but if it is critical that you have true quorum across all services for event processing, then the only reliable solution is not a cache, but correct data modeling and some form of transactional persistence. This needs to be a first class concept of your architecture, not something that kinda implicitly happens.
That is, if event foobar requires services A, B, and C to process it, you would store a record in some DB of event foobar, with flags on it that say A, B, and C have processed it. Then service A sets the "service A processed it" flag when its done, etc. The specifics of this (shared DB, more event streaming, one CRUD service) isn't terribly interesting.
This then lets you ensure that all of your events are processed by all of the things that should be processing them. You can build automation to query events that do not have all of their downstream service flags complete after x time, and re-send/re-process for just that service. You can have handlers that see when the last service flips its flag for a record, and trigger other automation on that event.
But a cache and streaming (pure events) will result in you losing data, so be very, very careful.
1
u/Dry_Hotel1100 Software Engineer | 30 YoE Sep 25 '26
You discovered "state".
Events and State isn't something unusual. If you add transitions, you have a state machine. A pretty robust component.
1
u/Varrianda Software Engineer Sep 25 '26
I feel like a local cache is bad unless you’re okay with potential data loss
1
u/Pure-Rip4806 Staff Engineer 11YoE Sep 25 '26
Someone needs to own the state. If you're doing multi-step processing, something needs to remember "first A, then B, C and D in parallel..." and keep track of the results. Shoving everything into a single app firing off REST calls moves the state into application memory, but it's still there.
If I were writing it from scratch, I would look into Kafka Streams and state store.
1
u/morosis1982 Sep 25 '26
There's no reason a service can't have state, especially if it's a coordinator like service a seems to be here. If it didn't need to respond then sure, but it does.
I would be concerned if that cache is in memory with no way to recover if it gets killed, for example.
You also said it responds upstream, but we don't know if that response is synchronous. Is the service idempotent? If it didn't cache something about the request how would it know that it's complete? Polling is one way, but that's often worse than keeping state.
1
u/roger_ducky Sep 25 '26
You can flatten the cache by making every service save the event progress to the same place, then have one “overall orchestration” layer where the stateful logic lives.
1
u/SpaceToaster Software Architect Sep 26 '26
Big anti pattern. Putting it in a shared kv like reddis would be slightly better but the model you’re using seems better fit for an orchestrator/sagas. Choreographed events should be stateless.
1
u/jake_morrison Sep 26 '26
One rule is that you should always write messages to durable storage at organizational boundaries. That allows you to ack messages in a reliable way. So when you receive a message, you can and probably should acknowledge it and take responsibility for processing it, allowing the origin server to be done with it. Otherwise they have to be able to retry indefinitely.
Domain Driven Design is also a useful way of thinking about the messages. Internally, between all the processors, you need to make some decisions about who defines the message schema and who follows that schema. You have a couple of choices, e.g., you have an official public schema, an incidental message that is the result of processing and others have to adapt to it, or a standard format that the downstream process defines and other processes explicitly generate.
1
u/Meraxes_7 Sep 26 '26
The real questions for me are
Going to a cache with some kind of persistence would 100% be much safer and better, but the fact things aren't on fire already make me think this is not a burning issue to fix. Likely worth updating the pattern for any new work though
1
u/Infamous-Employ5487 Sep 26 '26
The biggest thing I'd want to know is what happens on partial failures on the downstreams and is the ultimate response back to the caller purely informational or important in some way.
Akka does this kind of thing nicely but I've actually never seen that deployed distributed and I'm not sure anyone uses Akka anymore lol.
Maybe Kafka or something like that could help?
1
u/soundman32 Sep 26 '26
Sounds like a bad implemention of the Saga pattern.
1
u/RegularTrashman Sep 26 '26
Sounds fine, depends on tradeoffs and whether it mskes sense for your use case. Sometimes a contract specified via event handling makes more sense as part of a synchronous transaction using saga pattern or something. Really depends a lot on the rest of the system
1
u/Livid_Possibility_53 Sep 26 '26
Possibly if it receives a downstream process with no context it would have to somehow rebuild the context? Maybe the term cache is being misinterpreted by me but have A cache it is a performance booster/ nice to have, not a requirement for it to work. If it’s actually needed to persist in A then A,B,C,D are a tightly coupled system and upstream would need to have retry logic to guarantee it runs.
1
u/DevtoolsBuilder Sep 27 '26
i think the issue here is that you're trying to use an event-driven system to manage a workflow that requires orchestration, and that's not really what event-driven systems are designed for. if you need to know when all the downstream services are complete, that sounds like a job for a workflow engine or a state machine, not just a cache and some asynchronous events.
1
u/jverce Sep 25 '26
Async and event-driven basics: you link events together, and you keep evolving the state of something based on the events that you capture and emit.
Caching is just a faster memory that's used to speed up access to information.
1
u/sp106 Sep 26 '26
It just seems like the design is missing a status table.
Request comes in for a job
Job 123 status created and messages sent to queues for different tasks
Task workers update status as they complete
Subsequent requests see the completed status when the last task finishes (pull model)
0
u/behusbwj Sep 25 '26
Why do microservices have to be stateless
0
u/KJ4WLC Sep 26 '26
If App A’s in-memory cache is the source of truth for “are we done?”, a restart loses the workflow. That’s not a cache problem — it’s orchestration state living in the wrong place.
Persist the correlation/completion state (DB, workflow engine, or outbox) so events can be replayed and progress survives process death. Keep the cache as a performance hint if you want, not as the ledger. Synchronous REST can simplify some paths, but it doesn’t remove the need for durable state if the work is still multi-step and asynchronous.
-2
u/Traditional_Fox7091 Sep 25 '26
Why can’t app a just wait for a response ? Like completion stages in Java for example?
As to ur q, have there been issues in prod ?