iTranslated by AI
Best Practices for Effectively Once Batch Processing Design
This article is for Day 25 of the FOLIO Advent Calendar 2022.
It is a continuation of the 12/20 article The Story of How Batches Running on 4RAP Exceeded 300 Types - Part 1 -.
Introduction
In Part 1, I introduced the design history (ADR) regarding the macro-architecture of why 4RAP (specifically the component 4RAP-IA) adopted a batch system.
Now, as a micro-architecture topic, I would like to introduce practices in batch processing design.
This article is based on the experience of a single product in a specific industry called 4RAP.
While I cannot guarantee that the methods described will work for everyone, I hope they will be helpful to those who read it.
Batch Processing Design Practices in 4RAP
First of all, what are "practices" in batch processing?
A search brings up various results, and many people introduce different practices. (Reference: Thinking about batch processing - Qiita: Let's think about the adoption and design of batch processing)
I have a feeling this might become a degraded version of existing articles, but yamrkz's article covers the perspectives comprehensively and was suitable for explanation, so I would like to introduce the batch processing practices in 4RAP following its structure.
Batch Processing Practices
yamrkz's article introduces the following 11 perspectives:

Quote: Batch Processing Practices
In this article, I would like to discuss the following 6 perspectives among them:
- Trigger
- Retry & Logical Design
- Performance
- Monitoring
- Documentation
1. Trigger
Most of 4RAP's batches (80–90%) belong to workflows called "pipelines" internally.
For example, even for what is simply called "end-of-day processing" performed at the end of the day, there are processes with different contexts that are expected to be executed as a set, such as:
- Calculating and persisting the balance as of the start of the next day
- Switching the date
Since performing these in a single batch process is undesirable from various perspectives, we manage execution in units of pipelines that group multiple batches.

While pipelines are basically the same as batch processing triggers, a unique circumstance for 4RAP is the integration with systems of the client financial institutions.
For example, consider a case where we receive files from a client financial institution every night and import them into 4RAP.
Normally, files are sent around 10:00 PM, but on month-ends or days with high transaction volumes, it often goes past midnight.
We could set the 4RAP side's receiving process to 1:00 AM... but we'd prefer to receive and validate the data as early as possible.[1]
Therefore, the pipeline for importing files from client financial institutions uses two conditions as a trigger:
- Firing multiple times (e.g., between 10:00 PM and 1:00 AM)
- The existence of the file
This allows validation at the earliest possible timing—around 10:00 PM normally, or around midnight if delayed for some reason.
Note that it is necessary to detect an anomaly if the trigger conditions are not met by the final firing time. (It is not a problem if the trigger conditions are not met due to file absence before that.)
In 4RAP, we determine a deadline time for file absence and detect an anomaly if trigger conditions are not met during executions after that time.
2. Retry & Logical Design
In 4RAP, we adopt "Effectively Once" for retries.
Effectively Once is a concept provided by Apache Pulsar, where:
- A message is identified 100% uniquely,[2]
- Messages can be received at least once even during any failure,
- And it is always processed exactly once.
(Original source here)
Since it was originally a concept in messaging middleware, we have adapted it at 4RAP to fit the batch context as follows:
- Input data is identified 100% uniquely,
- Input data becomes the target of processing at least once,
- And it is always processed exactly once.
This is the principle of our retry design.
When Effectively Once is achieved, even if a batch process is executed multiple times by mistake or as part of troubleshooting, it is guaranteed to be processed only once.
Having Effectively Once guaranteed makes operations much easier; for example, even when correcting a portion of execution data as introduced in Part 1, re-running the batch without much thought ensures that there is no impact on data that has already been successfully processed.
So, what considerations are needed in logical design to achieve Effectively Once in batch processing?
First, to have "input data identified 100% uniquely," some kind of ID must be assigned to all input data.
Ensuring "input data becomes the target of processing at least once" is covered by considerations like the multiple firing described in the Trigger section for batch processing.
And to ensure it is "always processed exactly once," some record must be kept so that it's possible to determine whether the input data has been processed—meaning the ID of the input data must be linked to the output data.
If the above is guaranteed in the logical design, the process follows this logic: arrive at input data → extract ID from input data → search for output data linked to that input ID → if absent, perform processing; if present, skip processing.
These are the necessary and sufficient conditions to achieve Effectively Once in batch processing.

Now, it's just a matter of proceeding with the logical design... but I would like to introduce some points to be careful about during design.
A. Thoroughly Avoid Distributed Transactions
When achieving Effectively Once, we use output data to determine if processing is complete. However, if you have a distributed transaction, there is a possibility that the output becomes incomplete when a failure occurs.

To deal with this seriously in design, you would need to implement the Saga pattern. However, the Saga pattern is a complex mechanism with high operational difficulty, and I believe it is not a design that should be adopted in a batch system, at least.
You might consider the Saga pattern overkill and decide to cover it through operations while accepting the risk, as it's a rare occurrence... but it is quite difficult to correctly grasp the intermediate state of where a distributed transaction stopped during a failure. Operational difficulty increases significantly (especially if it happens in the middle of the night when you're half-asleep... a secondary disaster is unavoidable).
Moreover, since it's a rare event, by the time it happens, much time may have passed since the launch, and it might be forgotten or there may be no one left who knows the situation at the time. (Scary!)
Looking at long-term operation, there is really nothing good about distributed transactions... so it is at the top of my list of configurations to avoid during design.
That said, if you honestly break down business requirements, there are cases where distributed transactions seem unavoidable, right? (Humans are capable, so they can handle such complex processing.)
Next, I'll introduce several patterns I usually use to change the design to an Effectively Once batch system while avoiding distributed transactions.
Simply Split the Batch
If you've reached a design with distributed transactions, it probably means you can tolerate eventual consistency.
The simplest solution is to split the processing into two batches based on transaction units.
This solves cases where you don't care about the creation order of output data as long as there is eventual consistency.

You might worry that increasing the number of batches increases development and operational costs.
Regarding development costs, I find that two simple batches are often easier to develop in parallel and place less cognitive load during testing and review than one complex batch, so the cost increase is surprisingly low.
As for operational costs, experience shows that the number of failures does not correlate with the number of simple batches, so it almost never increases. (In fact, simplicity might reduce cognitive load and prevent failures.)
It's an empirical rule, but the disadvantages of splitting have never outweighed the advantages. (At least, no disadvantages have manifested.)
Therefore, rather than creating a complex batch process with distributed transactions, I would split it cleanly. (That's why we have 300 types.)
Pipeline
If output data "a" depends on output data "A," you would configure a pipeline with batch processes X and Y.
In this case, batch process Y's input data needs to be "A," but since you can trace back to input data #1 from the source data information held by "A," no information is lost even if you change to a pipeline.

Stream or Polling
What if you can tolerate eventual consistency but don't want the processing intervals to be too long? (This was an actual requirement.)
In that case, you would either make batch process X output to a queue for event-driven processing, or if a queue is difficult, shorten the polling interval of batch process Y.

Allowing Distributed Transactions
Most distributed transactions can be (and have been) eliminated by the methods above, but there are rare cases where we allowed a distributed transaction.
The case was:
- There is one input data
- A file is distributed
- There are N distribution destinations, and N is variable
- The data contained in the file is different for each of the N destinations

In this specific case, the following points were bottlenecks that forced us to accept a distributed transaction:
- Distribution to multiple variable systems
- The transaction scope could not be changed from the file unit
In practice, this case was managed because:
- Idempotency was guaranteed when overwriting files
- The subsequent processes at the distribution destinations were independent of each other
Because these two points were guaranteed, even if processing stopped halfway for some reason, simply re-running the batch was sufficient, and operational difficulty did not increase. (All's well that ends well.)
However, it's not always possible to do this, so if I come up with a better way to avoid distributed transactions, I'll write about it somewhere.
(Added on 2022/12/26)
Thinking about it, this case is a problem solved by a Pub/Sub configuration in the messaging world.
In a Pub/Sub configuration, the publishing process sends the message regardless of which system processes it, and the subscribing systems 1–N select the messages they need to process.

Translating this to the world of batch processing, it would look like the configuration below where output data is produced in one transaction, and systems 1–N that take the output data as input properly filter it. (Hereafter referred to as "Pub/Sub configuration in batch processing.")

While this resolves the distributed transaction, there are potential downsides:
- Mixing of data through the common area
- Increased operational difficulty due to multiple systems depending on a single piece of data (e.g., a failure in System 1's data → accidentally modifying System N's data → causing a secondary failure in System N)
This would be a point of trade-off in design. (End of 2022/12/26 addition)
B. Retrofitting Consistency
Moving slightly away from distributed transactions, there are also data where we want proper consistency rather than eventual consistency. (I certainly had such cases.)
For example, the pipeline related to balances performed at the end of the day in 4RAP includes various types of batch processes:
- Batch process X = Calculate the balance at the start of the next day
- Batch process Y = Calculate the valuation gain/loss at the start of the next day
- ... (and many others)
If we try to make all outputs consistent within a single batch process, we would give birth to a monster batch that references diverse data and holds a massive transaction.
Basically, we want these calculation results to align through eventual consistency.
On the other hand, we want to show customers consistent information rather than mismatched data, such as the next day's balance combined with the previous day's valuation gain/loss.[3]
At 4RAP, we handled this by assigning a common version to the output data for which we want to ensure consistency.
In the previous example of the 4RAP pipeline, we adopt the concept of a "balance date" as the version.
When the date switch occurs, the data reference point switches from the previous day to the next day. Although the data is generated via eventual consistency, to the customer who references it by specifying a version, it appears as though the data was generated with consistency.

That concludes the introduction of Effectively Once as a principle for retry design and the practices of logical design for batch processing based on that principle.
3. Performance
When you achieve the Effectively Once principle in your design, there are many options for improving performance through design changes.
Since Effectively Once itself is a concept from the messaging world, it is possible to transition directly to stream processing (and from there to reactive systems). (As mentioned in Part 1, there are trade-offs as you would be sacrificing ease of operation.)
A lighter approach would be parallel processing within a batch or at the batch level.
Since all input data has an ID, multi-threaded processing within a batch is relatively easy to implement. (There are some minor design considerations, such as processing order issues.)
Parallelization at the batch level is similar. Which one to choose depends on the processing content (e.g., batch-level for memory-intensive processes, multi-threading otherwise).
Basically, steady daily improvement activities are the most important for performance, and our engineers are working hard on this. (Thanks!)
However, having high affinity with architectural changes as a last resort is a good point of design following the Effectively Once principle.
4. Monitoring
In Part 1, I stated that 4RAP emphasizes ease of operation, and early detection of failures is crucial to minimize the range of difficulty in troubleshooting.
Therefore, for example, we include at least one batch process for monitoring, called an "Error Monitor," within a pipeline.

An Error Monitor is, as the name suggests, a batch aimed at anomaly detection.
When incorporating it into a pipeline, it checks whether the results (output data) of the series of processes performed in that pipeline are in the state they should be.
For example, consider a pipeline with the following batch processes:
- Batch process #1: Normalize input data from system A and import it into the system.
- Batch process #2: Use the normalized data to output processed data for integration with system B.

In such a pipeline, what would be good for the Error Monitor to verify?
For example, suppose the pipeline is simply performing protocol conversion between System A and B.
In that case, one perspective would be to check if the count of input data matches the count of processed data to ensure no conversion was missed.
For example, suppose the input data is product order data from customers and the processed data is purchase order data to wholesalers.
In this case, to check for missed or excessive orders, you could verify that the sum of order quantities per product in the input data matches the sum of purchase quantities per product in the processed data.
By incorporating an Error Monitor that performs such verifications into the pipeline, the following benefits can be gained:
- Verification is possible from the perspective of a specific processing unit (like a pipeline) rather than just a single batch.
- Verifying immediately after batch processing limits the scope where defects occur (if verification fails, there's a high probability the preceding batch is at fault).
- It becomes easier to investigate when failures occur in subsequent batch processes (since you can assume the state up to the Error Monitor was successful).
- Verification from the perspective of previously occurred failures can also be introduced.
Especially the last point is like incorporating automated tests into production operations, which can minimize damage even if a regression occurs, so I personally highly recommend it.
5. Documentation
There are likely various schools of thought on how to keep documentation, but at 4RAP (at least for now), we proceed by leaving design documentation quite thoroughly.
This is because, although development of 4RAP has progressed significantly and the end is in sight, we are still in the phase of assembling the MVP.
Systems are often categorized into SoE (System of Engagement) and SoR (System of Record), and in the MVP assembly phase, the vast majority of development belongs to SoR. (Since validation for engagement only becomes possible once the MVP is ready.)
And what is required for SoR is to implement the "common sense" (of the domain) as a matter of course.
However, domain common sense is not common sense for engineers. (It's rare for the two to coincide.)
Therefore, in an environment where code and tests are the ultimate truth, there is no way to grasp what the "common sense" of the SoR was, and the risk of the code becoming something no one can touch increases.[4]
4RAP aims for stable operation over the long term and emphasizes ease of operation.
Therefore, regarding SoR functions—the parts of 4RAP built so far—we have made a conscious effort not to neglect documentation.
Actually, while we create a large volume of documentation and continue maintenance, I feel that there has been a return worth the cost, such as preventing misunderstandings of business requirements by implementers and shortening investigation time during failures.
Conclusion
In this article, I have introduced the practices of batch processing design following the Effectively Once principle based on 4RAP's experience. What do you think?
I believe that the methods introduced here are working well for 4RAP so far...
but they are only an account of a very specific area.
I would like to refine them further, so if you have any insights such as:
- This is how we do it in my industry.
- This method cannot handle this kind of case.
- I tried it and it worked/didn't work.
I would be very grateful if you could share your knowledge.
Happy New Year, everyone!
-
4RAP is a product that is added on to the existing systems of client financial institutions.
Due to its nature, it must start processing after the existing system's overnight processing is finished and complete the processing in time for business the next day, so there isn't much time to spare.
This lack of time margin for troubleshooting is the background of the design to detect data irregularities early and maximize the time available for recovery work. ↩︎ -
The first item in the original is "Identify and discard duplicated messages with 100% accuracy," but since the third item, "...but effects on the resulting state will be observed only once," includes the meaning of discarding duplicates, I have intentionally paraphrased it to focus only on identifying messages. ↩︎
-
For example, if a customer is shown a mixture of current day and next day information during an update, it could induce incorrect investment decisions. Therefore, display data must be as consistent as possible. ↩︎
-
While tests can guarantee quality according to the initial "common sense," if the external environment (e.g., laws) changes, the "common sense" changes accordingly.
To keep tests aligned with the new "common sense," I believe some kind of documentation is necessary (at least for SoR). ↩︎
Discussion