Immutability #
Immutability is fundamental to efficient data processing, encountered at the design and implementation levels. Let’s explore these scenarios individually.
Design #
Point-to-point microservices share data through endpoint calls, CQRS and event-sourcing are popular designs that use data immutability as a core principle. In these types of systems, resilience is achieved through the processing of queued messages using worker instances. The data is only inserted through the command, and the response is created from one-to-many inserted records.
In event streaming designs, the pattern is similar—stored immutable messages in topics are “realized” into new data. New messages added to the topics trigger events to transform and combine data. These events are then processed by different services to address different business needs.
Both designs minimize data mutation by creating new “immutable” states, preventing race conditions when updating/persisting data to databases. This avoids potential database locks or, worst, data-loss caused by overrides.
Implementation #
Imperative procedural code and long methods is a recipe for “spaghetti.” Usually, the recipe follows the following: variables are declared at the top of the function and mutated multiple times through assignments in cascading loops. Variable mutations take a toll on our working memory.
Preventing re-assignment of variables makes the code easier to read as it requires less working memory to remember all the logic permutations. Functional programming is ideal for implementing code that creates only immutable states using operations like Map, Filter, and Reduce. Current modern languages embrace functional operations to create immutable variables, including Java and Javascript. Especially on the JVM, Immutability is paramount to implement multithreaded applications, as mutated shared-state between threads can have nasty side effects that are extremely hard to reproduce.
Take away #
The benefits of Immutability are many, ranging from improved performance to code quality. When designing or implementing services, Immutability is a best-practice, and the tradeoffs of ignoring it need careful consideration.