Skip to content
ImagineWorld

A S ample E

node_idnode-book_ai-ready-postgresql-18_chapter-03-a-s-ample-e
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleA S ample E
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Throughout this book, we will use a single sample application to demonstrate how developers can build high-performance transactional, analytical, and AI applications using PostgreSQL. The sample application executes sales transactions across multiple geographies, consolidates them for centralized analytics, and utilizes AI to generate purchase recommendations.

This chapter details the application as well as its use cases, data models, microservices architecture, and coding conventions that we’ll follow throughout this book.

We encourage you to install the sample database application to follow along with the coding examples throughout the book.

All the code required to run the sample application is available in the GitHub repository, along with the container that includes PostgreSQL 18 and all the extensions we will use in this book. Every chapter that includes code samples has a separate file containing the code, clearly linked to the sections in the chapter.

The sample application is designed to run on PostgreSQL version 18. Developers who want to practice the AI examples need an OpenAI API key. The Readme.md file provides detailed instructions for setting up the sample application.

Our sample application creates and executes e-commerce transactions for an apparel business through regional microservices. The data from those services is aggregated into centralized analytics and AI services. The sample app is built on five intercommunicating data services, as shown in Figure 3.1 that leverage logical replication and foreign data wrapper capabilities to communicate.

Let’s start with a short overview of the services, before diving into their data models and integration points:

  • A centralized reference data service manages product definitions and prices, distributing them to the geographic e-commerce systems and to the centralized AI and analytics services
  • East Coast customers use the East Coast e-commerce database to browse products and create sales transactions
  • There is a West Coast e-commerce database for West Coast-based customers
  • There is a centralized analytics service to provide a unified and near-real-time view across the business
  • There is a centralized AI database that generates AI-driven purchase recommendations and provides a natural language interface to the product catalog

The following diagram illustrates how these five database microservices interact within the overall architecture.

Figure 3.1: Five database microservices

For the sake of this book, all databases are created on the same server; in production, the architecture would be implemented across multiple servers to spread the load and provide horizontal scalability. Small, low-volume applications might be able to use a single database, but that will not provide the foundation for future scalability and isolation of services that might compete for resources.

The following sections provide a detailed explanation of the various data services, including their data models and the methods they employ to utilize logical replication and foreign data wrappers for data sharing.

The application is set up as five modular data services that share data using logical replication and Foreign Data Wrappers. Let’s review each service and its data model.

The e-commerce application utilizes a centralized product and price definition to ensure that customers across all regions have an accurate, near-real-time view of prices and product information, as seen in Figure 3.2. We use PostgreSQL logical replication to share data among our e-commerce, analytics, and AI services.

Figure 3.2: ERD for the product reference data

If we inspect the ERD in Figure 3.2, we can see that the key tables and columns are the following:

  • product manages items, such as Men’s Classic Oxford Shirt, that people search for. Products have labels and short and long descriptions.
  • product_variant describes different versions of the product, such as Men’s Classic Oxford Shirt in size medium, blue.
  • product_variant_price contains the prices for product variants for a given date range (the price’s validity). Only current prices will be replicated to the e-commerce databases. The complete pricing history will be replicated to the central analytics database. The centralized reference data service provides two publications:
    1. The e-commerce product publication publishes all current product prices to the transaction sites. Any historical or future data is filtered out at the row level. 2. The analytics publication does not apply any filtering and is used by the central analytics and the AI data services.

Customers on the East and West Coasts can browse products and place online orders, which are reflected as sales transactions and transaction lines. Both e-commerce sites also maintain a table of available inventory.

The product schema, including all of its tables, is identical and replicated from the reference database.

Inventory data is tracked in the product_variant_inventory table. For example, the current inventory comprises 12 units of the product variant Men’s Classic Oxford Shirt in medium size and blue color.

Customer data is managed in the customer table.

Figure 3.3: ERD for the East Coast e-commerce service

The e-commerce sites subscribe to the central reference data service’s e-commerce product publication.

They each share their customer and sales data through a publication. The central analytics service subscribes to those publications.

The central analytics database as seen in Figure 3.4, merges product, customer, and sales data to enable near-real-time unified analytics, providing a single source of truth for the business.

The product, customer, and sales data are replicated from the reference data service and the e-commerce services into schemas and tables that are identical to the source structures. The tables in central analytics serve as the foundation for denormalized analytics-focused data models that support cubes, rollups, and stars to accelerate and simplify analytics-oriented queries.

Figure 3.4: ERD for central analytics

Central analytics gets its data through three subscriptions:

  • The product and price data subscriptions, which connect to publications from the reference data service
  • The customer and sales transaction data subscription connects to the customer and sales publication from the East Coast e-commerce service
  • The customer and sales transaction data subscription connects to the customer and sales publication from the West Coast e-commerce service

The centralized AI service generates purchase recommendations and supports a natural language query interface to the product catalog. To generate those recommendations and queries, it replicates the product data. It augments it with a set of tables to store embeddings that represent the semantics of the product data as shown in Figure 3.5.

Figure 3.5: The ERD for the AI database

The AI database subscribes to the product data published by the reference database. It exposes views that generate product recommendations and support a natural language interface to the database. Those views can be accessed by the application or called via a foreign data wrapper.

Each microservice includes an API schema that isolates the user from the implementation details, allowing for a more modular and scalable architecture. The API defines an insert/update/delete function for every table in the service that the application or other users modify, as well as one or more views for those tables. For example, the product price table is managed in the e-commerce reference data service. It exposes a management API, but that API is not available in the other microservices because the reference data is handled only in this microservice. The API schema does not contain any tables. The central analytics and AI services provide only read-only APIs.

The use of the database as the core building block for microservices, along with the use of API schemas as the application programming interface, is described in detail in , Database Requirements for High Volume Transactional Applications.

To help you understand how to implement authentication, authorization, and auditing in PostgreSQL, we define a set of users (individuals or applications that connect to the database) and groups, which specify the permissions for users to access and potentially modify data.

In PostgreSQL, user and group are aliases for role; a user is a role with login privileges.

Table 3.1 outlines the users and groups, as well as their roles and responsibilities, for the sample application. Chapter 4, Database Requirements for High Volume Transactional Applications, explains how to leverage these definitions to create a differentiated security and access control model.

RoleResponsibilities
Master DBACreates and manages databases and roles
Application DBACreates and manages schemas, tables, procedures, and functions in the databases managed by the Master DBA
Replication UserDefines and operates the publications and subscriptions that replicate data between the e-commerce reference service, the e-commerce services, and the central analytics service
Product ManagerDefines products, product variants, brands, and categories in the e-commerce reference database
Product Price ManagerManages the product variant pricing Has read access to product information in the e-commerce reference database
Inventory ManagerManages the product variant inventory levels in the East Coast and West Coast e-commerce services
eCommerce ApplicationCreates/reads/updates/deletes sales transactions in the East and West Coast e-commerce services Has read-only access to the product information that is replicated to the e-commerce sites
AnalystHas read-only access to views in the central analytics service Has no access to any other data

Table 3.1: Users and their roles

Coding conventions are fundamental when creating larger applications that will be maintained over an extended period. They make it easier to understand the original developer’s intentions and to find any flaws in the logic.

Some programming languages, such as Python, have established coding conventions that are generally accepted and must be followed. PostgreSQL is much more flexible and does not prescribe coding, formatting, or naming conventions. This is why we chose to share the conventions we use in our work with customers, as well as in the sample application used for this book and in the examples in the following chapters.

The recommended conventions apply to the spelling of identifiers. They also provide naming conventions for databases, schemas, tables, columns, functions, stored procedures, and API definitions, as well as recommendations for code comments.

Identifiers are the names developers assign to tables, columns, variables, and so on. Some rules apply to all identifiers; other rules, described later, are specific to the nature of the identifier (a table, a column, or the name of a variable in the body of a stored procedure).

All identifiers are lowercase. Even if you use uppercase in your code, PostgreSQL will interpret it as lowercase unless you enclose the identifier in double quotes, which can lead to confusion, mainly when the database is accessed from case-sensitive application development languages.

This example, using different cases for the identifier product, illustrates the potential problem:

product = Product = PRODUCT != "Product" != "PRODUCT"

The first three spellings of the identifier product will all be interpreted as referring to the same thing, as the PostgreSQL parser will lowercase the identifier product before passing it to the planner and executor. The last two spellings will not be lowercased because they are enclosed in double quotes; they will be treated as two distinct identifiers.

All PostgreSQL identifiers start with a letter or an underscore (**_). The maximum length for an identifier is 63 bytes.

For complex identifiers,we recommend using snake_case. This is true for databases, schemas, tables, views, columns, constraints, indexes, functions, procedures, variables, and so on.

For example, use product_price instead of productprice, as it greatly improves readability.

Names, even more so than spelling conventions, are key to conveying design decisions and architectural considerations. We recommend that developers adopt the following conventions:

  • Table names are singular, for example, product instead of products.
  • Column names should be singular and meaningful and avoid abbreviations; for example, use description instead of desc.
  • Primary keys, especially synthetic keys that are used as primary keys, are called id (preferred) or < table _ name > _ id.
  • Foreign key references should combine the table name and the column name using snake case notation. For example, product_id refers to the id column in the product table. In the definition for the price table, this could be used as follows to identify the foreign key:
CREATE TABLE price
(
...,
product_id REFERENCES product (id),
...
)
  • Function names start with sf_, except for the create/update/delete functions defined as part of the API schema (see the following code block).
  • Procedure names start with sp _.
  • Temporary table names start with temp_.
  • View names start with vw _.
  • Materialized view names start with mv_.
  • PostgreSQL keywords are always capitalized, as in the following example:
SELECT id, description
FROM product
WHERE description ILIKE '%jeans%'
ORDER BY description ASC;

Databases should have meaningful names that are associated with the business purpose, for example, hr or ecommerce. Schemas should be used to manage related concepts inside a single namespace.

Here is an example:

CREATE SCHEMA product;
CREATE TABLE product.category (id integer,..);
CREATE TABLE product.brand (id integer,...);
...
CREATE SCHEMA sales;
CREATE TABLE sales.order(id integer,...);
CREATE TABLE sales.order_lines(...);
...

PostgreSQL enables developers to embed business logic directly within the database. This provides a very effective and efficient way to create complex data management procedures. PostgreSQL supports both functions and procedures, which will be covered in Chapter 6, Functions and Stored Procedures. To improve readability and manageability, we use the following coding and naming standards:

  • Parameter names are prefixed with p_
  • Internal variable names are prefixed with v_

Here is an example:

CREATE PROCEDURE product.sp_calculate_price (p_id INTEGER) AS
$$
DECLARE
v_new_price NUMERIC;
...
BEGIN
...
$$ LANGUAGE PLPGSQL

We always recommend using named parameters for function and procedure definitions. Avoid using positional parameter references.

The body of a procedure or function is defined as a string constant, conventionally delineated by $$. For improved readability, the $$ can also be replaced by $function $ or any other string embedded between two $ signs, as shown in the code below:

CREATE PROCEDURE product.sp_calculate_price (p_id INTEGER) AS
$sp_calculate_price$
DECLARE
v_new_price NUMERIC;
...
BEGIN
...
$sp_calculate_price$ LANGUAGE PLPGSQL

Databases that follow the microservices architecture described in , Database Requirements for High Volume Transactional Applications expose an API schema that contains the application interface to the database. By default, the API exposes create/read/update/delete functionality. Application calls should be limited to the functionality exposed by the API schema. This can be enforced through security and visibility restrictions.

Create/ u pdate/ d elete functionality should be implemented through a uniform stored procedure or function. In this book, we will use a function, manage_ < table name >, whose first parameter is the operation type (INSERT, UPDATE, DELETE), followed by parameters for the table columns. The return type is TABLE with JSONB columns for the old column and the new column.

Here is an example:

CREATE OR REPLACE FUNCTION api.manage_product_category (
p_operation_type TEXT,
p_id INTEGER DEFAULT NULL,
p_label VARCHAR(50) DEFAULT NULL,
p_description TEXT DEFAULT NULL
)
RETURNS TABLE (
operation_type TEXT,
old_value JSONB,
new_value JSONB
)
AS $$
…
$$ LANGUAGE PLPGSQL;

Read access is implemented through a view, < table _ name > _ vw, or a materialized view, < table _ name > _ mv.

Here is an example:

CREATE OR REPLACE VIEW api.vw_catgory AS
SELECT id, label, description FROM category;

We highly recommend spelling out all the column names that should be included in a view. Do not use SELECT * FROM < table >; this may yield unexpected results if the underlying table changes.

Comments are critical in PostgreSQL code, just like in any other programming language. They are key to making code maintainable and debuggable. We recommend the following conventions:

  • Single-line comments are limited to 80 characters and use -- to indicate a comment line (-- tells the parser to ignore the rest of the line).
  • Multi-line comments use the /* ... */ convention. Individual lines are limited to a maximum of 80 characters.

Here are some examples:

-- This is a single-line comment. The line is less than 80 characters long
/*
================================================================================
This schema defines the product reference data. The tables are:
- category, e.g., pants, shirts, polos, sweaters
- brand, e.g., Boss, Levis, The Gap, ...
- product, e.g., a blue shirt from Boss
- product_price, with information about the date ranges when the price was
applicable
================================================================================
*/

Installing the e-commerce sample application

Section titled “Installing the e-commerce sample application”

The application can be installed by the GitHub repository associated with the book, the GitHub repository associated with the book,following the instructions in the README.md file to set up the example in a VM or Docker container with the necessary PostgreSQL extensions. The repo provides the Dockerfile and the Compose commands to create a container with all the necessary extensions.

We strongly recommend that you download and install the sample application so you can follow the examples step by step and learn how to use PostgreSQL effectively to build high-performance transactional, analytical, and AI applications.

Be aware that the sample application requires PostgreSQL 18 (or later) to illustrate new PostgreSQL capabilities, such as RETURNING NEW/OLD for queries and the UUIDV7() function to generate universally unique IDs.

The sample application and the coding conventions outlined in this chapter establish the foundation for the upcoming chapters. , Database Requirements for High Volume Transactional Applications will use the sample application scenario to show how to build a highly scalable PostgreSQL architecture that is secure and auditable and supports agile development processes.