Skip to content
ImagineWorld

Database Requirements for High-Volume Transactional Applications

node_idnode-book_ai-ready-postgresql-18_chapter-04-database-requirements-for-high-volume-transactional-applicat
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titleDatabase Requirements for High-Volume Transactional Applications
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 4 — Database Requirements for High-Volume Transactional Applications

Section titled “Chapter 4 — Database Requirements for High-Volume Transactional Applications”

Database Requirements for High-Volume Transactional Applications

Section titled “Database Requirements for High-Volume Transactional Applications”

Modern transactional applications face a unique set of challenges. They must handle high volumes of concurrent requests in global environments while guaranteeing ACID compliance and consistent performance. At the same time, enterprises expect systems to be agile, able to adapt quickly to new business requirements, and secure, with strict auditing and access controls in place.

For many years, the default answer was to consolidate data into a single, central database. While this made reporting easier, it also created monoliths that were slow to evolve, difficult to scale, and were bottlenecks to innovation. Even minor schema changes required coordinated updates across every application, slowing innovation and increasing risk.

PostgreSQL offers a way forward. With its mature transactional engine, flexible schema and API support, replication features, and strong ecosystem, it provides the building blocks for creating data services that are reliable, scalable, and developer-friendly.

In this chapter, we’ll look at the key database requirements for high-volume transactional applications and show how PostgreSQL 18 can be used to do the following:

  • Scale effectively without sacrificing consistency
  • Define modular structures that allow teams to move fast
  • Support efficient cross-service data sharing and aggregation
  • Implement robust security and auditing with minimal overhead

We will begin by describing the required capabilities and then demonstrate how they can be implemented in PostgreSQL. A final section will show how such a PostgreSQL microservices architecture can be secured and audited.

Your purchase includes a free PDF copy + code bundle

All examples in the chapter are available in the GitHub repo under psql_scripts / sample_scripts / chapter_4.sql.

Why microservices need a smarter database architecture

Section titled “Why microservices need a smarter database architecture”

Traditionally, businesses have tried to bring all their data together to create a single source of truth: one place to find all the data about customers, products, purchases, prices, discounts, and areas of the business that are more profitable. These databases grew into huge monoliths that were slow to change, presented significant operational challenges, and could not keep up with business demands. The database became a bottleneck for innovation instead of an enabler.

Microservices emerged as a key application architecture over 10 years ago. This architecture pattern decouples functionality, allowing parallel teams to work independently, and enables scaling capacity up and down by deploying fleets of microservices.

However, when microservices are applied to the data layer, many organizations fall into one of two traps. In some cases, microservices are all deployed against a single monolithic database, which keeps the data model rigid and slows down innovation. In other cases, the database model mirrors the application microservice architecture one-for-one, which creates performance and efficiency issues. Neither approach unlocks the full benefits of microservices.

When we map microservice applications to monolithic databases, we still lack the necessary flexibility in the data model. Introducing new data elements (let’s say a flexible phone number field that allows customers to store multiple phone numbers) can take months, as every other application in the company that requires access to the field also needs to change, and those changes must all be deployed at the same time. The fact that many systems do not allow for downtime any longer makes this even more challenging.

When the database model is mapped rigidly to the application services, then we risk getting suboptimal performance.

To illustrate this, consider an imaginary scooter rental company (SRC) that has created four microservices to manage scooter availability, as shown in Table 4.1.

ServiceDescription
Service A: Scooter scheduleWhich scooter is available when?
Service B: Scooter maintenanceWhich scooter has what mileage and services, and when is it scheduled for service?
Service C: Scooter locationWhere is which scooter right now, and where has it been over time?
Service D: Scooter modelsWhat are the properties of the different scooter models?

Table 4.1: SRC scooter rental microservices

Each microservice has its own PostgreSQL database. On the surface, this seems correct, but in practice, it is next to impossible to answer simple requests efficiently. For example, a user asks, ” Can I rent a scooter m odel 5 in l ocation X at 2:00 PM?”. To answer this question, the application must do the following:

  1. Ask Service A (scooter schedule) if there are model 5 scooters available at 2:00 PM.
  2. Check with Service B (scooter maintenance) to remove those that are due for maintenance today.
  3. Check whether any of the available ones are in location X by asking Service C (scooter location).

Because the data services are not integrated, the applications contain significant amounts of code to run the three queries, filter the result sets, and find an available device.

All of this can be avoided by using PostgreSQL’s built-in capabilities. Using f oreign d ata w rappers (FDWs), the scooter schedule database could directly reference data from the maintenance and location databases. With this approach, a single SQL query could answer the question of availability. The application code is minimal, query performance is excellent, and the feature will be delivered to market quickly.

Using PostgreSQL to create successful microservices data architectures

Section titled “Using PostgreSQL to create successful microservices data architectures”

PostgreSQL provides the building blocks for scalable, reliable, and agile data architectures that address the three key architectural challenges:

  • Effective scalability
  • Modular APIs to give development teams the ability to move fast
  • Efficient cross-service data sharing and aggregation

Let’s have a look at each of these in detail below:

To support high-volume workloads, relational transactional databases can be scaled horizontally by breaking them into smaller components that run on separate servers. PostgreSQL provides two practical approaches for scaling:

  • Modular services that can be distributed to multiple servers. For example, if the scooter schedule service needs more capacity, it can be moved to a separate server while the other services continue to share the original hardware.
  • Fleets of services that work in parallel. For example, when the rental business explodes, we create three separate instances for the East Coast, the West Coast, and the Midwest.

Both approaches allow for a flexible distribution of workloads across servers. In PostgreSQL, we can use the database server, the database, or the schema as building blocks for modularization and scaling. This is clearly demonstrated in Figure 4.1 below:

Figure 4.1: The hierarchy of data representation objects in PostgreSQL

Download the color images

We recommend using the PostgreSQL database as the foundation for modularization, as it allows us to use the schema to create separate namespaces and to define APIs inside the database-level module (We will cover this in detail in the following section on modular APIs). It also means that the communication protocol between modules (logical replication and FDW) does not change when modules move to other servers or dedicated servers.

By implementing each data service as its own database, services can be co-located with others on the same server or moved to a separate server to avoid noisy-neighbor problems and allow them to scale independently. When needed, we can use logical replication to migrate services to another server with near-zero downtime. Pg_dump / pg_restore can also be used, but it implies downtime.

When fleets of microservices are required (that is, when we must create multiple occurrences of the same service), we distribute the workload across natural shards, such as East Coast customers or West Coast customers, and we share reference data, such as product definitions and prices. Logical replication is our preferred tool to set this up, especially since PostgreSQL 17 automated the failover of replication slots. To provide a single point of truth, we aggregate the results from the sharded services into a single analytics service (see Figure 4.2). Again, we use logical replication for that purpose.

Figure 4.2: Modular database services using logical replication to share data

The four databases shown in Figure 4.2 could share a server or be distributed across separate servers. The data architecture and the logical replication architectures would not change, except for the network addresses in the replication definitions. As the business expands, the e-commerce service can be further distributed into fleets of services for customers in the Midwest, Southeast, and Northeast.

Using the database as the foundation 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.

Relational databases, such as PostgreSQL, offer many ways to separate the public API from its internal implementation. We have chosen schemas as the way to provide a public API using views, functions, and procedures. This allows us to hide and isolate the actual implementation details from the application. For example, in Figure 4.3, only the API schema is accessible (using the access control mechanism described later). The schemas for customer, sales, product reference, and inventory are accessed via the functions and views defined in the API schema. This isolation can be further strengthened using PostgreSQL’s Security Definer feature and limiting the roles that have any access to other schemas.

Figure 4.3: Schemas for modularization within databases

Schemas also support creating API versions, and the schema search path can be used to switch new connections to the next version of the API.

For example, two schemas, api1 and api2, can contain the same view vw_data_access. Here, api1 has the current version, and api2.vw_data_access is the updated version. Initially, the search path points to api1, so SELECT * FROM vw _data_access``; accesses the view in api1. When it comes time to switch over to the new version of the API, we change the default search path, and all new sessions automatically start using the view in api2.

Supporting efficient cross-service data sharing and aggregation

Section titled “Supporting efficient cross-service data sharing and aggregation”

The scooter rental example described previously illustrates the problem that occurs when cross-service sharing is disabled at the data level. PostgreSQL provides two convenient approaches for sharing data between services:

  • FDW s make it easy for one service to leverage data that is managed by another service. The FDW creates a table that can be queried as if it were local, but in reality, the requests are forwarded to a remote service. There is no data duplication, but the services should run in a low-latency, highly reliable environment.
  • Logical r eplication (LR) uses a change data capture mechanism within a publish-subscribe framework built on PostgreSQL’s write-ahead log (WAL) to distribute changes. LR supports row- and column-level filtering. LR does not require low-latency environments and can handle temporary network disconnects, but it duplicates data and can cause temporary inconsistencies between the source and target.

In our e-commerce example, we use LR to share product reference data with the fleet of e-commerce services and to assemble their transactional data into an integrated analytics environment. We use FDWs to access the AI shopping recommendations provided by the centralized AI service (see Figure 4.5). The schemas shown in Figure 4.3 serve as the building blocks for distributing data, and as we shall see, also for re-aggregating it.

LR, in combination with table partitioning, can also be used to re-aggregate the data into a single source of truth. For example, customer data is partitioned into East Customer and West Customer and then merged into a single table.

Here’s how we define three customer tables:

  • east_ customer.customer holds the customer data from the East Coast data service
  • west_ customer.customer holds the customer data from the West Coast
  • merged.customer uses east_ customer.customer and west_ customer.customer as two partitions.

merged.customer can be queried for east and west data, and hides this data aggregation from the data user. When a new data service is added, we simply add a new partition, and queries will continue to work seamlessly.

Figure 4.4: Using LR and table partitioning to re-integrate data into a central location.

The PostgreSQL search path helps us avoid duplicating API code. The customer views in all three databases refer to the customer table, but the search path ensures that the views operate on east_ customer.customer west_ customer.customer, and, respectively, merged_ customer.customer. This effectively hides the internal implementation from the application, which is exactly what we want.

PostgreSQL constructs to bring it all together

Section titled “PostgreSQL constructs to bring it all together”

We have seen how databases, schemas, APIs, FDWs, and LR help us build modular, scalable data services, and the role of each building block. This section explains how they work together to create a complete, working system.

APIs and interfaces define how the application instances connect with the database, and how different data services – defined as PostgreSQL databases – interface with each other:

  • Applications connect to the data service APIs via libpq or another PostgreSQL driver. While application microservices connect to data microservices, there is no implied 1:1 relationship between them. Application instances can scale up and down rapidly, and several instances can share one data service via a connection pooler, such as PgBouncer, as seen in Figure 4.5.
  • APIs are defined using PostgreSQL schemas, including views, functions, and procedures.
  • APIs can be versioned, and the PostgreSQL search path is used to redirect new sessions to new versions of the API, without disconnecting currently running sessions.

Modules and d ata s ervices are accessed via the APIs and can be distributed onto different servers for scalability. They also define areas of responsibility for development teams, allowing them to move fast and remain agile.

Each data service should use its own PostgreSQL database as the basic building block. This makes scaling and isolation straightforward.

Data services can be offloaded to separate servers, allowing them to scale independently and isolate them from noisy neighbors. As PostgreSQL does not offer a resource manager, we have to resort to OS or VM mechanisms!

Data services can form a fleet of replicated (or sharded) services to scale individual data domains.

Cross-service d ata m anagement capabilities are essential for distributing reference data, aggregating transactional data into single points of truth for analytics, and enabling data services to call on each other:

  • Data services can call on each other using FDWs to allow for efficient cross-service data requests. FDW calls should leverage the defined APIs to avoid the tight coupling of data services.
  • Reference data, such as model definitions or price lists, are logically replicated across different domains to allow for efficient querying. This also makes it easier to maintain referential integrity.
  • Data from fleets of services can be reintegrated into central points of truth using LR.

Figure 4.5: Data microservices and application microservices.

Figure 4.5 shows how the building blocks come together to create modular, scalable, and agile architectures, and which PostgreSQL capabilities can be used to develop such architectures.

Modularity, scalability, and agility are key, but the resulting system also needs to be secure and protect data from unauthorized access.

The previous section has demonstrated how microservices, built on databases, schemas, and API definitions, offer an effective way to scale and support agile development. This section introduces a systematic framework for database security, known as **Authentication,****Authorization,**and Audit (AAA). A systematic approach is critical because microservices distributed across the network can create more potential points of attack. There are more connection points, APIs, and moving parts in a microservices architecture compared to a monolith. A systematic and scalable approach is key.

While there is a broader security context, such as physical access to the server, network access to the server, encryption of data in transit, and encryption at rest, that must be addressed in a production deployment, this book will focus on the PostgreSQL database itself.

AAA provides a step-by-step methodology that leverages PostgreSQL capabilities and uses the microservices’ data domain definitions to implement a scalable, manageable security model:

  • Authentication: The database verifies who the user (or application) is and ensures they have the right to connect. For example, the user is Jane Doe, a member of the Product Managers group and of the team responsible for product price management. She is a known user and has the right to connect.
  • Authorization: The database tracks which privileges have been granted to specific roles or individuals, and it prevents unauthorized access to database resources. For example, product managers have read/write access to the product information via the API functions manage_brand and manage_product, but only product price managers have access to the manage_product_variant_price API function. Jane Doe is a member of the latter group and can change prices.
  • Auditing: Key transactions are tracked as audit statements in the log and are identified as such to easily separate them from errors and other system log statements. For example, every product price change is tracked as an audit statement, including the name of the person who made the change and the date it was made.

The microservices architecture helps us with this task, as AAA rules can be defined by a data service rather than against a monolith. For example, whoever manages product definitions in the product reference service may (or may not) have the same responsibility for inventory levels in the east commerce service.

AAA encompasses role-based access control (RBAC) and extends it with auditing definitions.

Authentication identifies users and applications. It answers this question: Who is connecting to the database? PostgreSQL can use its own password mechanism or integrate with LDAP, Kerberos, Active Directory, and OAuth (new in PostgreSQL 18) to authenticate users. It can also use mTLS certificates, which are frequently used to secure bidirectional communication between applications. The access control definitions in the hba.conf configuration file play a major role in determining which PostgreSQL users require which authentication methods.

Authorization, REVOKE, GRANT, and the principle of least privilege

Section titled “Authorization, REVOKE, GRANT, and the principle of least privilege”

Authorization builds on authentication. Once we know who has connected to the database, we need to understand what rights they have. Authorizations in PostgreSQL are handled through two concepts: roles and privileges.

The SQL standard defines users and groups, which can be grouped into roles, which can then be structured hierarchically to define complex structures. For example, a user can be a member of both the product management and analyst roles, which would give them read/write access to product data and read-only access to sales reports.

The clear separation between roles, including hierarchies of roles and individual users, is a very important concept that helps make access control manageable.

PostgreSQL supports this with a twist. Instead of a clear distinction between users and roles, it defines roles with login privileges (users) and roles without login privileges, which are used to manage and control data access (a.k.a. groups). PostgreSQL also provides two aliases: users and groups:

  • CREATE USER is an alias for CREATE ROLE WITH LOGIN
  • CREATE GROUP is an alias for CREATE ROLE WITH NOLOGIN

We recommend using CREATE USER to define roles with login privileges and CREATE ROLE otherwise. This makes it easier to read, understand, and maintain.

Access controls (that is, the rights that are conferred to a role) should always be defined at the role level – never at the user level. This is important because individual users may change roles, and several individuals can share the responsibilities assigned to a role. For example, if Jane Doe is a master DBA who has super user privileges and then moves into product management and is now in charge of product price management, then her change of role should be managed by moving her from the Master DBA role to the Product Price Management role, without having to inspect her individual user privileges. Similarly, new hires or departures should be handled at the group level.

Groups can be hierarchical, as in this example:

--- create a group for all product management users
CREATE ROLE product_management;
--- create a user
CREATE USER jim_miller
IN ROLE product_management;
--- create a sub-group to manage prices
CREATE ROLE product_price_management
INHERIT --- automatically inherits the privileges of the product management
IN ROLE product_management;
--- create a user who has the privileges of the price manager
--- and implicitly inherits other rights from the product management group role
CREATE USER jane_doe
IN ROLE product_price_management;

In PostgreSQL, the assignment of privileges is handled through the GRANT and REVOKE commands. As a best practice, we recommend using the principle of least privilege. This takes two steps:

  • Revoke all default privileges, not just those considered unnecessary.
  • Grant only the privileges that are needed.

First, we revoke all default privileges that are assigned to PUBLIC, a role that includes all other roles.

REVOKE CONNECT ON DATABASE ecommerce_reference_data FROM PUBLIC;
REVOKE USAGE ON SCHEMA internal,product, api FROM PUBLIC;
REVOKE EXECUTE ON PROCEDURE api.update_current_price_flags FROM PUBLIC;
REVOKE EXECUTE ON FUNCTION
api.manage_product_price,
api.manage_product,
api.manage_brand,
api.manage_category
FROM PUBLIC;

Then, we explicitly assign the privileges necessary for the members of both roles to do their job:

--- allow the group role to connect to the reference data service
--- product_price_management will automatically inherit that privilege
GRANT CONNECT ON DATABASE ecommerce_reference_data TO product_management;
--- allow the group role to see all the objects in the API schema
GRANT USAGE ON SCHEMA api TO product_management;
--- allow read access on all tables and views in the API schema
GRANT SELECT ON ALL TABLES IN SCHEMA api TO product_management;
--- only members of the product_price_management role can call the
--- api.manage_product_price functions to change pricing
--- these functions run with the SECURITY DEFINER property
GRANT EXECUTE ON FUNCTION
api.manage_product_price,
TO product_price_management;
GRANT EXECUTE ON PROCEDURE
api.update_current_price_flags
TO product_price_management;

This approach makes sure that no user can bypass the API, and that only authorized users (that is, those in the price management team) can update product prices.

Auditing means to keep track of who did what when, for example, who increased the price on a product on Friday morning during the Black Friday sale? We recommend a mindful, business-driven, and differentiated approach to auditing. Instead of simply setting log_statement = all, which would log every query and DDL statement, seriously impacting performance, consuming enormous amounts of disk space, and providing a completely unusable amount of information, we suggest a tiered approach:

  • For lightweight visibility into schema changes, log_statement = ' ddl ' can be sufficient
  • When you need audit-grade, business-relevant tracking, use the PostgreSQL extension pgAudit selectively, scoping it to the actions and objects that matter

There is no general rule for what should be audited – the business context defines this. For example, in an HR system, it may be necessary to track every SELECT access to the salary table. In an e-commerce system, one would closely audit customer-specific discounts. Audit data is often manageable using PostgreSQL’s csvlog format and tools such as file_fdw for analysis, and it can be exported to a separate system so that querying audit records does not compete with production workloads.

In our example, we recommend auditing all DDL commands, all data changes to product information (insert, update, and delete) in the product reference microservice, and all changes to the inventory tables in the e-commerce services. In central analytics, we recommend tracking every access to any views in the API schema.

pgAudit is a popular extension to audit specific objects and session activity. To set up the auditing parameters described previously with pgAudit for the e-commerce reference service, we state the following:

CREATE EXTENSION pgaudit;
CREATE ROLE auditor;
ALTER SYSTEM SET pgaudit.role = 'auditor';
-- log all ddl operations on all objects
ALTER SYSTEM SET audit.pgaudit.log ='ddl';
\c ecommerce_reference_data
-- use object-level auditing for DML on product related tables
GRANT INSERT, UPDATE, DELETE
ON
product.product,
product.brand,
product.category,
product.product_variant,
product.product_variant_price
TO auditor;
-- pgAudit does not support object-level auditing for functions or procedures
-- audit all function and procedure calls for this database
ALTER DATABASE SET audit.pgaudit.log ='function';

We leverage pgAudit ‘s object-level auditing for tables and views. pgAudit has two drawbacks:

  • Object-level logging is not available in pgAudit for functions and procedures, so we use general audit logging for all executable components instead
  • pgAudit writes audit information to the PostgreSQL log file rather than to a separate audit log

The recommended AAA methodology leverages the data microservices definitions for the Authori z ation and Auditing rules. At the same time, the modular microservices approach makes it easier to manage those rules. Instead of a single, comprehensive set of rules for a large monolith with many roles, we can use specific guidelines for each module that handle a smaller set of roles, objects, and operations:

  • Authorizations are defined separately for each data microservice. For example, Jane from product price management only has access to the reference data service. Jane is not mentioned in any other service; all product price managers have no privileges in those services. Remember that the least privilege approach removes all access first and then grants only the necessary privileges. Thus, if Jane is not mentioned, then she has no rights.
  • Auditing rules are also microservice-specific. Because prices can only be changed in the reference data service, we also focus audit rules on price changes there. Similarly, reports on customer purchases are available only in the central analytics service, and only analysts have access to it. This simplifies the rules significantly.
  • Authentication is ideally handled outside of the database infrastructure. While hba.conf can specify requirements (e.g., that all product managers must be LDAP-authenticated), authentication should not be performed at the database level.

In this chapter, we showed how microservices can be used to create modular architectures that are highly scalable and support agile development.

By using the database as the core construct for modularization, the schema to define the API, and logical replication, combined with FDWs, to enable cross-service communication, we can create highly flexible dataservices. LR helps us share reference data and create referential integrity in a distributed system. The same technology can then be used to reaggregate all the data into a central source of truth for analytics and AI.

Creating this type of modular and distributable architecture may result in higher operational complexity, but it provides the foundation for scalability and geodistribution – a must-have for many modern enterprise applications.

Besides scalability and transactional integrity, security is the other must-have. Using the AAA methodology, we laid out a clear path for using PostgreSQL’s hierarchical roles, which work in conjunction with the built-in privilege system, to create a secure environment that implements the principle of least privilege and leverages a microservices architecture.

The next chapter focuses on the ACID-compliant transactions, functions, and stored procedures that bring the microservices architecture to life.