Microservices in Postgres

Microservices provide a great architectural foundation to create a scalable data and AI platform

Vibhor Kumar and Marc Linster

Postgres at the heart of your microservices architecture

Great, big monolithic databases that assembled all the company’s data used to be considered a good thing. When I was Technical Director at Digital Equipment (a long time ago), our business goal was to bring ‘it’ all together into one enormous database instance, so that we could get a handle on the different businesses and have a clear picture of the current state of affairs. We were dreaming of one place where we could see which components were used where, what product was more profitable, and what parts of the business could be evaluated and optimized.

What changed? Why do we now consider monoliths to be dinosaurs that inhibit progress and that should be replaced with a new micro-services architecture?

This article reviews the pros and cons associated with large, monolithic databases, before diving into modular database (micro-)services. We review their advantages and challenges, describe a real-world problem from our consulting background, and outline design principles. The article ends with a discussion of Postgres building blocks for microservices.

Why did we ever want the big monolithic database?

Every business I know has been struggling with uniform definitions, such as a uniform price list with historical prices, or a single source of truth, such as the definitive list of customers and their purchases. Trying to move all the data into one ginormous system with referential integrity is very tempting, and when it works, it can be very rewarding.

There are also other operational benefits, such as a single maintenance window, a single set of operating instructions, a single vendor, and a single change management process.
However, this centralized approach begins to show its limitations as the database grows to an extreme scale, leading to performance bottlenecks and inflexibility.

The challenges of monolithic systems are significant, and many architects believe that the challenges outweigh the benefits. Data volumes are continuously increasing, while the number of users and applications requiring data access also grows. This trend, driven by the demand for improved user and service experiences, is resulting in a fundamental rethinking of system design

Let us start with the most important operational challenges:

  • Backup and recovery can be very slow and cumbersome as it takes a lot of time to spool the data to disk, and move the copy off site. The same is true when trying to recover a database. The industry has developed work arounds, such as database snapshots, incremental backups and delayed replicas — but they are workarounds that add complexity without addressing the fundamental issue of a single, massive recovery domain.
  • Upgrades take a lot of time for two reasons: (1) the actual software upgrade process can take a lot of time, and (2) testing all the business applications that use the single point of truth for functional and non-functional issues is a lengthy process often freezing the business from deploying other critical features for weeks or months at a time
  • Single monolithic databases have limited scaling options as the CPU, the IO, and the memory tend to be bottlenecks. There are ways to mitigate the problem, such as Oracle RAC or Postgres multi-master replication, but they require proprietary infrastructure (e.g., Oracle RAC) or have limited scalability potential (Postgres multi-master replication). NoSQL vendors have adopted new consistency paradigms, such as Eventual Consistency, but that approach is not applicable to many transactional systems that have to support the ACID paradigm and need immediate consistency.
  • Huge databases tend to become fickle and have to be treated with extra care. Only a small team of ‘database high priests’ knows how to keep them operational. They are definitely pets — sometimes very moody and difficult pets — and not cattle.

There are also significant innovation challenges:

  • The monolith cannot keep up with acquisitions, divestitures, and changes in business process. It takes too long to integrate and align the data into a single system.
  • Change management processes become enormously complex when any change can potentially touch every function in the company. For example, there is no way to quickly change the discount model to react to a competitor’s new pricing, when it takes weeks (or even months) to understand the ripple effect.

Almost every company we have worked with has walked away or is planning to abandon the monolithic approach — it’s just too cumbersome and slow.

Database microservices

Breaking up the monolith into smaller databases that can be developed, governed, and operated somewhat independently is the goal of database microservices. The challenge is how to do that while maintaining ACID compliant reads and writes, achieving high availability, and avoiding read/write amplification as outlined in https://momjian.us/main/writings/pgsql/microservices.pdf.

It is not always advisable to drive the microservices concept to the extreme, as we learned in working with a customer. For confidentiality reasons I will describe them as a scooter rental company. They had created microservices with individual micro databases that did not integrate at the database level:

  1. Scooter Schedule: which scooter was available when?
  2. Scooter Maintenance: which scooter had what mileage and services, and when was it scheduled for service?
  3. Scooter Location: where is which scooter right now, and where has it been over time?
  4. Scooter Models: what are the properties of the different scooter models?

It became next to impossible to answer simple requests efficiently: “Can I rent a scooter Model 5 in Location X at 2:00 PM?”, as their application had to:

  1. Ask data service A (Scooter Schedule) if there were Model 5 scooters available at 2:00 PM
  2. Check with B (Scooter Maintenance) to remove those that were due for maintenance today
  3. Check if any of the available ones were in Location X by asking C (Scooter Location).

As their data services were not integrated, they had to write a significant amount of code to run the three queries inside their microservices applications, maintain the data sets, create execution plans, and find an available device. Their project failed before they even encountered the snapshot isolation issues described in https://theartofpostgresql.com/ by Dimitri Fontaine.

All of this could have been avoided by creating a single view in database (A) that used FDWs (Foreign Data Wrapper) to (B) and (C) to run one single query. The code for the scooter availability question would have been minimal, the performance would have been terrific, and the project likely a success.

It is obvious how to do that in a database monolith. In this article, we explore how to do that using database microservices.

Based on our experience we have identified four key problems that need to be solved to use Postgres (or any other relational database) to create database microservices.

  1. Achieve effective scalability
  2. Define clear modular APIs to give teams the ability to move fast
  3. Support efficient cross-service data sharing
  4. Aggregate information across services

All of that while maintaining ACID compliance!

Achieving Effective Scalability

ACID compliant databases do not scale well horizontally. Proprietary technologies such as Oracle RAC can help achieve scalability but they are limited to proprietary platforms with shared storage (which could be a single point of failure) and are extremely costly. Bi-directional replication in Postgres can help achieve limited scalability, but it is mostly focused on high availability, near-zero downtime maintenance and geographic distribution. Eventual consistency approaches, such as those used in MongoDB and other NoSQL solutions, are scalable but do not always meet the needs of transactional business applications.

In relational architectures we differentiate two approaches to scaling:

  1. Modular services that can be distributed across multiple servers. For example the Scooter Schedule service runs on server A, and the Scooter Maintenance Service runs on Scooter B.
  2. Multiple copies of the same service to work in parallel. In our example, this would mean that we define several instances of the Scooter Schedule service and distribute the load across those instances.

Both approaches allow for a flexible distribution of workloads across servers. In Postgres, we could use the database server, the database, or the schema as building blocks for modularization and scaling.

Hierarchy of data definitions in Postgres

We recommend using the ‘database’ as the foundation for modularization as it allows us to use the ‘schema’ to define namespaces and APIs inside the database-level module (see next section). It also means that the communication protocol between modules (logical replication, FDW, and DBLink), does not change when modules move to other servers or dedicated servers.

By implementing every data domain as its own database, the domain can be co-located with other domains on one server, or it can be moved to a separate server to avoid noisy neighbor problems and allow it to scale independently. Logical replication provides a near-zero downtime way to move a database to another server.

Using the ‘database’ as the modularization tool

In the scooter rental example outlined above, we can start with three databases on the same server. When scheduling traffic increases, we move the Scooter Schedule service to a dedicated instance.

Moving a module (a microservice) to a new instance for scalability

When business takes off, we create an East Coast instance and a West Coast instance for the Scooter Schedule service.

Creating two instances of a microservice for scalability

Using the database as the basis for modularization and scaling also works well in containerized and virtualized environments where we have seen a growing adoption of the one database/one server architecture.

Defining Modular APIs

Relational databases, such as Postgres, offer limited ways to separate the public API from its internal implementation. In https://momjian.us/main/writings/pgsql/microservices.pdf, Bruce Momjian outlines how schemas can be used to provide a public API through views and functions, while the actual implementation of the views and functions, and the table definitions, happen in a private schema that is not visible to the public.

Using the schema to segregate API and implementation

Supporting efficient cross-service data sharing

In the example outlined above, our customer’s implementation failed because they didn’t allow for data services to share data across domains — all data integration and cross-domain queries had to be handled through the application. This led to enormous complexity, and caused what Bruce Momjian calls ‘Call Amplification’.

Postgres, and other databases, provide robust ways to allow databases to share data and requests.

We differentiate two key architecture patterns:

  • Supporting cross-service queries: “Show me all Model 5 scooters that are available in Location X at 2:00 PM”
  • Sharing reference data, such as product definitions. For example: “Scooter Model 5 has a basket and can carry up to 20 lbs on the rear luggage rack”.

Cross-service requests

In Postgres queries across data services can be handled through FDWs that make it easy to define and execute requests that impact more than one data domain. Such requests can be implemented either by extending the API of one service — for example through a view defined in the Scooter Schedule service that integrates the data from the other services, or by creating a separate aggregator service that focuses on defining and executing requests across multiple data domains. FDWs are Postgres’ implementation of the SQL/MED standard.

FDWs see a lot of innovation and provide a future proof way of defining modular databases and their push-down capabilities make them very efficient.

Postgres also provides DBLink as a technique to forward requests to another database. While DBLink has very powerful capabilities, they have not seen significant focus lately. DBLink allows one database to invoke a function or stored procedure on another database, for example the Scooter Maintenance service could call the scooter_commit function in the Scooter Schedule service to update a schedule. Generally, we would recommend that such update transactions should be invoked directly from the application to avoid ‘integration spaghetti’.

We consider FDWs as the primary way of database servers interfacing with each other, and in a microservices architecture, we recommend limiting those interactions read-only requests

Shared reference data

While FDWs could be used to access reference data, for example the Scooter Model definitions remotely, this will provide significant network traffic and will create suboptimal query performance. We recommend sharing such reference data using logical replication, so that the local queries inside each data service have direct access to reference data.

Integrating shared reference data using dedicated schemas

Aggregating Data Across Services for Analytics

The architecture described above provides ways to define modular and scalable services. The last challenge is how to aggregate the data to achieve a single source of truth. In our example above, this would include bringing together the schedules from East Coast and West Coast locations into a Centralized Analytics service.

Postgres provides two options:

  1. We could implement a materialized view that leverages two FDWs to pull the data from the East Coast and West Coast servers into the centralized analytics service. The materialized view aggregates the data, and optimizes it for analytics.
  2. We can replicate the data from the East Coast and West Coast Services using logical replication, and then aggregate it locally using a view or a materialized view.

We recommend option (2) as it is more efficient and can provide a current view of the data that is almost real time. It is also more tolerant of high latency networks. Option (1) replicates the data every time the materialized view is refreshed, which causes significant network traffic and overhead on the source and target systems. Option (1) only replicates the changed data and is more efficient. Options (1) could potentially be combined with extensions, such as pg_ivm, that automatically update materialized views.

Bringing it all together

Guidelines:

  • The microservices connect to the data services via libpq, Postgres’ standard API, potentially mediated by a connection pooler. They connect to the public API schema that every data service exposes. For read requests, we use views (or materialized views). create/update/delete requests are handled via functions or stored procedures that are exposed in the public schema. This encapsulates the implementation details and allows agile development.
  • Every data domain is handled through a separate database, which allows for independent maintenance and deployment schedules, deals with the noisy neighbor syndrome, and allows for independent scaling.
  • Data domains can be replicated (or sharded) to scale individual domains beyond the limits of a single database server, and to bring data closer to the user.
  • A special aggregation service handles queries across multiple domains. It uses FDWs to issue multi-database requests.
  • Reference data, such as model definitions or price lists, are replicated to the different domains to allow for efficient querying. This also makes it easier to maintain referential integrity.
  • Facts and reference data are replicated to a centralized analytics service for efficient cross-domain analytics queries.
Integrated microservices architecture with Postgres, using databases and schemas to achieve modularity and isolation

Caveats

Logical Replication is a powerful tool in Postgres. However, the developer has to be aware of its limitations:

  1. Logical replication cannot replicate data from views or materialized views — thus the publication from the domain services to the central analytics will build on the tables in the private schema. Tables, rows, and columns can be filtered out — but the publication definition will reveal (and rely) on tables defined in the private schema.
  2. Logical replication cannot (currently) rename tables. For logical replication, the table name is the fully qualified table name, which includes the schema name. The documentation states:

The tables are matched between the publisher and the subscriber using the fully qualified table name. Replication to differently-named tables on the subscriber is not supported
(
https://www.postgresql.org/docs/18/logical-replication-subscription.html).

This means that in order to assemble the data from multiple instances of the same service into one analytics service, the schema names in the origin service must be unique. For example in the East Coast Scheduling Service, the schema name could be east_coast_schedule, and west_coast_schedule in the West Coast Scheduling Service. Both schema names have to be defined verbatim in the database of the analytics service. Within the analytics service, a partitioned table can then use tables from these different schemas as its partitions, providing a single, unified view of the data.

This requirement impacts the implementation of the local APIs, as the private schemas in the source databases must have these unique names.

Summary

Postgres provides a robust toolset to define modular databases that support microservices architectures. Using servers, databases, and schemas in combination with FDWs and logical replication we can achieve scalable, modular, and agile data management solutions that are ACID compliant, maintain referential, and can be deployed anywhere.