Skip to main content
Polyglot Persistence at Scale for E-Commerce
Back to Blog

Polyglot Persistence at Scale for E-Commerce

Overview

Architects implement a range of databases, including SQL, document, graph, key-value and wide column as well as time series. They apply SAGA, change data capture and operational rigor to ensure that these diverse data stores work effectively together as a ‘polyglot’ solution. Although offering the benefits of a variety of databases, a multi-database solution increases the complexity of distributed systems compared to a monolithic approach. Poor service demarcation, absence of idempotency and lack of standardised observability can lead to fragile bi-directional data synchronisation, undetected data drift and unwelcome incident escalation.

Background

Historically, normalised relational databases have dominated data modelling in enterprises. Services have used these for their rigid schema definition, foreign key dependencies and ACID (Atomicity, Consistency, Isolation, Durability) functionality to accurately represent information such as financial values, stock levels and identities. Vertical expansion – upgrading to higher specification hardware – was sufficient to manage expansion for many years. However, web and mobile usage, plus real time analysis and streaming now place increased pressure on systems. Single node expansion and a reliance on rigid schemas were both shown to have limitations.

During the late 2000s and 2010s there was a movement away from the belief that relational data modelling was always essential. Informed by the CAP theorem (any distributed system must sacrifice either consistency or availability if it experiences a network partition) and PACELC (Partition – choose between availability and consistency; Else – balance latency and consistency), key-value, document, wide column and graph databases have been implemented. These cater for particular data access requirements.

Whilst there was initially a move to adopt NoSQL solutions, the industry has since moved towards deliberately utilising both SQL and NoSQL. Modern relational databases now incorporate JSONB data types and support sharding and read-replication. Specialist databases have further developed distributed consensus, replication and cloud capabilities. Today, the debate is less about SQL or NoSQL and more about what type of database is most appropriate for a particular bounded context, in a manner which does not unduly increase operational complexity.

Understanding Polyglot Persistence

Polyglot persistence sees a combination of database types being utilised by and/or within an organisation. Each database is allocated to a service or bounded context based on how well it can cater for that context’s data and access requirements. Data is owned by individual services and the most appropriate database is therefore selected according to a service’s latency, consistency and expansion requirements.

Importantly, polyglot persistence enables separation of:

Expansion

A high-write service such as a telemetry or click-stream service can be horizontally expanded, whereas an accounting service will likely be more conservatively expanded and will place a high priority on durability.

Domain alignment

Document databases are effective for representing hierarchical information such as product data. Likewise, graph databases neatly represent complex inter-relationships such as those seen in social and supply chain data. This avoids the inefficiencies of object relational mapping and multiple join operations.

Failure isolation

Increased demand for recommendations or search indexation should not affect the connection pools used for checkout operations.

However, note that, whilst polyglot persistence is relevant to bounded contexts, it does not permit each development squad to arbitrarily select a preferred database. Further database types increase an organisation's maintenance, verification, query optimisation and cross-database consistency requirements.

Overview of Key Database Types

Database selection should be informed by a service’s read and write operations, query requirements, concurrency, retention and consistency requirements, not simply by market desirability.

Relational (SQL)

Relational databases (including PostgreSQL and MySQL) comprise tables of structured data related to each other. Foreign keys, indexes and robust ACID functionality are all supported. They are adept at multi-table transactions, and can perform highly sophisticated querying. Furthermore, they can reject invalid data at the point of writing to uphold integrity. Nevertheless, there are challenges around horizontally expanding write operations, particularly when table joins and global constraints exist and nodes are spread widely.

Document

Document databases (for example, MongoDB) utilise semi-structured documents, commonly in JSON or BSON format. Objects and arrays can be nested within documents. This is particularly appropriate for information such as product data, user profiles and content which has differing attribute definitions. Unfortunately, they are not ideally placed for extensive cross-document querying and for rigid inter-document constraints – areas more appropriately addressed by a transactional database.

Key-Value / Cache

Key-value and cache databases (including Redis) provide fast (<1ms typically) access to values by referencing keys. These can be either unstructured or structured. Services use this type of database for managing sessions, restricting request rates, implementing distributed locking and for maintaining hot read caches. As queries generally relate to specific keys, these databases are highly performant and high throughput, but are not adept at relational query operations.

Graph

Graph databases (for instance, Neo4j) use nodes to represent data and define relationships between nodes as first class entities which can have properties. This allows for highly efficient and expressive multi-level relationship traversal. Services such as fraud detection, identity, permissions and recommendations benefit well from this, since the depth of relationships can be unpredictable. Often SQL databases require expensive self-joining or recursive operations to achieve equivalent multi-level relationship traversal and this performance deteriorates as graph complexity increases.

Wide Column

Wide column or column family databases (for example, Apache Cassandra and Amazon DynamoDB) shard data and order rows within shards according to clustering columns. They are designed for high write throughput, linear horizontal expansion and fast single-shard data access. Good advance definition of the data model is essential due to the high expense and/or non-support for ad-hoc cross-shard querying and aggregation.

Time Series

Time series databases (examples include TimescaleDB and InfluxDB) are optimised for time stamped data ingestion, together with compression and time window aggregation. They are used for infrastructure, industrial and financial sector telemetry and tick data analysis. Recent data is commonly analysed and older data is either down-sampled or expires according to retention policies. Again, however, these are not designed for general relational transaction operations, nor for arbitrary graph traversal.

Database Type Data Structure Key Feature(s) Trade-offs / Limitations Typical Enterprise Application
Relational (SQL) Tables, rows and relations High quality ACID functionality Horizontal write scaling challenges with complex joins/constraints Orders, billing and accounting, user accounts
Document JSON/BSON documents with nesting Variadic data schemas. Fast read and write operations Cross document transactions and querying are more expensive Products, CMS and dynamic profiles
Key-Value / Cache Key-value pairs. Time to Live (TTL) and atomic operations Ultra low latency and high throughput. Straightforward data access Limited query functionality. Memory pressure for large data sets Sessions, request throttling, hot caches and locks
Graph Nodes, edges and edge properties High performance multi-level relationship traversal Horizontal sharding of highly connected data hubs can be complex Fraud, permissions and recommendations
Wide Column Sharded rows. Clustering columns High throughput data writes. Linear horizontal expansion Schema should be query orientated. Ad-hoc relational cross-shard querying is limited Event logging, messaging and IoT ingestion
Time Series Time series with tags and/or fields Time window aggregation, retention and expiry functionality Not ideal for relational CRUD and graph traversal Metrics, observability and sensor telemetry

Technical Architecture and Design

Typically, several databases will be involved in response to a single business operation such as an order. However, it is generally unworkable to treat these as though they constitute a single database due to their heterogeneity. Architects therefore design systems with defined service demarcation, asynchronous data transfer and consistency agreements.

Example flowchart for services and databases

Client ["Client / API Gateway"] -->| | OrderSvc [Order Service]
Client -->| | CatalogSvc [Catalog Service]
Client -->| | SearchSvc [Search & Recs Service]

OrderSvc -->| | PG [PostgreSQL\nOrders & Payments]
CatalogSvc -->| | Mongo [MongoDB\nProduct Catalog]
CatalogSvc -->| | Redis [Redis\nHot Cache & Sessions]

PG -->|Transactional Outbox / CDC| Bus [Event Broker\n(Kafka)]
Mongo -->|Change Streams / CDC| Bus

Bus --> SearchSvc
SearchSvc -->| | SearchIdx [Search & Graph Store\nDiscovery & Fraud]

Consistency, Availability and Transactions

Strong consistency guarantees that all readers see the most recently committed data. Eventually consistent databases or derived databases will later synchronise, albeit asynchronously. Financial and seating booking data generally needs to be strongly consistent and contained within a transactional database. By contrast, search indexes, activity and analytical data can affordably be eventually consistent with milli- or secondary delays.

Two-phase commit (2PC) is used to co-ordinate database locks. Yet, blocking locks, coordinator failure and network latency between databases negatively affects availability and throughput in distributed systems. Typically, strong ACID transactions are confined to individual databases within a service. Cross-service operations are then orchestrated via the SAGA pattern – a series of local transactions which emit events or commands. Should any step in this process fail, compensating transactions are initiated to reverse previous steps in a meaningful way.

Data Synchronisation and Distributed Systems

Dual data writing – whereby an application writes data to two separate databases – is a common pitfall. If there is a service failure or timeout between these writes, data will become out-of-sync.

Robust architectures employ either CDC or a Transactional Outbox mechanism to synchronously commit data to a durable message broker following database local ACID transaction completion. Consumers can then asynchronously and idempotently refresh caches, search indexes and graph representations using event or version identifiers.

Despite advances, distributed systems continue to experience issues such as out-of-order message delivery, at-least-once re-processing and network partitions. Furthermore, traffic can become hotshotted (for example, if a particular item goes ‘viral’), causing uneven data distribution across database shards. Idempotency within consumers and oversight of consumer lag can help to ensure that temporary issues do not develop into persistent data inconsistencies.

Business Example Scenarios

Commerce & Fulfilment E-Commerce Platform

Imagine an enterprise e-commerce offering that facilitates flash sales and global fulfilment.

  • Order & Payment Ledger (PostgreSQL): Records order, invoicing and payment status. Strong ACID behaviour and row-level locking are applied to avoid double-charging.
  • Product Catalog (MongoDB): Stores detailed and locale specific product information along with category specific attributes. This information is frequently updated but can be changed without impeding catalog deployment.
  • Session, Shopping Basket and Hot Stock Cache (Redis): Provides a high read-rate service for shopping baskets, session identifiers and temporary request rate controls.
  • Search & Recommendation Graph (Search & Graph Stores): Both product attributes are indexed for instant search, and co-purchase and customer device data relationships are mapped to enable recommendation and fraud detection.

During checkout, an order saga locks stock, carries out payment authorisation and logs orders. Search availability and analytical tables are asynchronously refreshed via CDC events.

Financial Telemetry, Fraud and Audit Pipeline

Within a payments or banking environment, it is vital to simultaneously deliver low-latency risk assessment and rigorous audit functionality.

  • Account & Ledger Core (Relational Database): Imposes double entry controls and ensures strong consistency of financial values and settlement data.
  • Real Time Transaction & Device Events (Wide Column / Stream Store): High volumes of payment and telemetry data are ingested to allow rapid reference and historical re-play of functionality.
  • Entity & Relationship Graph (Graph Database): Analyzes multi-level connections between shared credit cards, IP addresses, merchants and account details to identify collusive fraud networks.
  • Immutable Audit & Event Log: Append-only data evolution is recorded to enable compliance teams to trace historical data states and investigate contention.

Operational Considerations

The success or otherwise of a polyglot persistence strategy can often be determined many months after architectural approval has been given.

Ensure service-specific database ownership

Prohibit services from directly accessing databases across a network. Instead, expose data via versioned APIs or curation of event streams. This allows safe schema evolution.

Establish standardised observability

Consistent metrics, distributed tracing (OpenTelemetry) and structured logging should be used to monitor query latency, connection pool utilisation, lock contention and replication and CDC consumer lags for all databases.

Perform regular automated data backup and restoration testing

An engine’s RPO (Recovery Point Objective – the maximum period of acceptable data loss) and RTO (Recovery Time Objective – the maximum period of acceptable downtime) must be practically validated by conducting restoration tests. This should be done for all database types.

Centralise schema and security management

Control schema evolution alongside application code. Apply least privilege access to each service. Automate secret management and ensure data is encrypted both in transit and at rest.

Ensure local and CI environments are representative

Replicate production languages, restrictions and migration scripts within local environments and/or test frameworks. Issues can thus be identified pre-staging.

Benefits, Drawbacks and Architectural Considerations

Dimension Benefit Cost / Consideration
Expansion Enable horizontal and/or vertical expansion for distinct data domains Expansion behaviours differ for various database types.
Autonomy Services can data-model in a natural fashion and independently deploy alterations Increased mental effort and wider skill set required.
Consistency Local strong ACID behaviour. Flexible eventual consistency for derived data. Complex compensation, idempotency and reconciliation.
Cost Avoids the need to provision a massive database to cater for all data access requirements. Multi-database licencing, cluster and under-utilisation costs may occur.

Common Pitfalls

  • Extending databases unnecessarily: New databases can be erroneously implemented for marginal ease of use even when extant relational functionality (such as indexing, sharding and/or JSON columns) could suffice.
  • Synchronous cross-database joins: Combining data from 4 different databases during a single front-end request increases tail latency and potential failure points.
  • Unobserved eventual consistency: Consumers may not be notified of outdated data. Moreover, financial processes may be built upon eventually consistent derived data without awareness of latency issues.
  • Lack of idempotency and dead-letter queue implementation: Retried events can cause double-charging. Likewise, erroneous messages may be discarded without entering dead-letter queues and being re-processed.

Best Practice

  • Introduce polyglots progressively: Only implement a second or third database when a service’s data, throughput and/or latency requirements demonstrably exceed the capabilities of an existing database.
  • Design for eventual consistency: Whilst confirming order completion to a consumer, asynchronously present progress updates regarding order fulfilment and search indexation in an elegant manner.
  • Automate reconciliation: Periodically cross-check source ledgers against derived data stores and/or caches to promptly detect and resolve data misalignment.
  • Clearly allocate ownership and define incident management: Each live database should have defined owners and alerting protocols together with proven incident management processes.

Future Directions and Architectural Innovation

Modern relational databases are continuing to assimilate additional data functionality, for example improved JSON, vector and distributed SQL support. This further raises the bar for justifying multi-database utilisation. Concurrently, data mesh approaches are decentralising data ownership to domain squads and considering analytical results as versioned products as opposed to merely dumping them into a data warehouse.

Furthermore, streaming CDC and event sourcing, alongside lakehouse structures, are helping to better integrate operational and analytical, and even AI, data processing. Rather than analysing live transactional data with intensive analytical queries, clean domain events are increasingly streamed into analytical tables and dedicated query data stores. Operational boundaries are simultaneously well maintained.

Conclusion

Polyglot persistence is an engineering consideration. Done well, it allows varied parts of a system to each utilise the database type which is most appropriate for a particular data set and access pattern. This provides strong consistency for key operations and allows search, cache, graph and telemetry to independently scale.

Key Messages

  • Analyse requirements before implementing new databases: Define a service’s read and write operations, latency service level agreement (SLA), consistency and expansion requirements. Firstly confirm that your current database is unable to adequately and neatly meet these requirements.
  • Ensure that each domain has a singular source-of-truth: Localise strong consistency and transactional controls. Avoid dual database writing from an application and instead use transactional outbox or CDC mechanisms. Consumers should also exhibit idempotency.
  • Invest in operations prior to horizontal expansion: Implement common operational functionality such as observability, alerting for consumer lag, automated data back-up and proven restoration procedures for all of the database types in operation.

FAQs

What is polyglot persistence?

It is the use of multiple database types within a system. Each dataset is stored in the database which is most appropriate, according to how that data is structured, queried and expanded.

Does polyglot persistence always mean each microservice uses its own database?

Not necessarily. Microservices with comparable relational and transactional requirements can safely share a database and/or schema. Additional databases are only implemented when a service’s data, throughput and/or latency requirements cannot adequately be met by an existing database.

How is data kept consistent across multiple databases?

Wherever feasible, confine strong ACID behaviour to single databases. Leverage transactional outbox or CDC mechanisms to securely broadcast data state modifications. Cross-service operations should be coordinated using SAGA and compensatory actions. Consumers should furthermore be idempotent.

In what situations should organisations avoid polyglot persistence?

Avoid it for nascent products and for smaller engineering functions. Where a single well-tuned database can already effectively address a service’s latency, concurrency and expansion requirements then there is no need for polyglot persistence, even if heroic measures would also be applicable.