Database Design

Understand data ownership and database isolation, choose cross-service queries, business snapshots, and read-only copies, and learn the constraints behind stock reservations.

🎯 Introduction

We have divided the store into users, orders, inventory, and simulated payments. Separating code is not enough if orders can still modify inventory tables directly: multiple services would still control inventory rules. A schema change in inventory could then require changes in orders.

This article asks: which data should each service manage, and how do we fulfill requirements such as order queries once data is separated? We use MySQL to explain isolation, then order details and reservations to explore cross-service queries, snapshots, and synchronization. Earlier courses covered MySQL syntax; here we focus on service boundaries.


🧱 How a Shared Database Can Undermine Independence

Suppose both orders and inventory can access stock. When a user orders, orders executes:

UPDATE stock SET available = available - 2 WHERE sku = 'A';

Meanwhile, inventory reserves and releases stock and ensures that available quantities never become negative. Two services now modify the same stock using different code.

For example, inventory may distinguish available and reserved quantities while orders still deducts available stock with old SQL. This can bypass reservation rules and obscure changes. Renaming inventory tables or columns could also immediately break the order SQL.

The problem is unclear data ownership, rather than MySQL itself. Orders owns order creation but crosses inventory's boundary to decide how stock changes.

Data ownership means the service responsible for business rules manages the corresponding data; other services use public APIs or business events. Orders can request a reservation of two units of A, but should not execute UPDATE against inventory tables.


🗄️ Assigning Databases to the Four Services

Start with the established business boundaries:

ServiceOwned dataHow other services use it
Usersusers (accounts and profiles)Call the user API
Ordersorders, order_items (orders and items)Call order APIs or receive order events
Inventorystock, reservations (stock and reservations)Request reservation, release, and other operations
Simulated paymentspayment_attempts (simulated payments)Call payment APIs or consume outcome events

Ownership does not mean others can never see the data. It identifies who modifies it, interprets it, and maintains its business rules.

Logical isolation within one MySQL instance

The teaching project needs no four physical servers. Create four databases in one MySQL instance:

MySQL instance
├── users_db
│   └── users
├── orders_db
│   ├── orders
│   └── order_items
├── inventory_db
│   ├── stock
│   └── reservations
└── payments_db
    └── payment_attempts

With an administrative account allowed to create databases, run:

CREATE DATABASE users_db;
CREATE DATABASE orders_db;
CREATE DATABASE inventory_db;
CREATE DATABASE payments_db;

In MySQL, CREATE DATABASE creates a database, also commonly called a schema. All four share one MySQL process but have separate ownership boundaries.

Creating databases alone is insufficient. If every service uses an administrator account with access to all databases, cross-database writes remain possible. Give each service its own account with permissions limited to its database. For example, inventory's grants could be:

-- This password is a placeholder; use a securely generated password in real environments.
CREATE USER 'inventory_app'@'%' IDENTIFIED BY 'REPLACE_WITH_STRONG_PASSWORD';
GRANT SELECT, INSERT, UPDATE, DELETE
ON inventory_db.* TO 'inventory_app'@'%';

inventory_app receives read/write permissions only for inventory_db, not orders_db. Apply the same principle to the other services. Manage schema-change privileges separately; ordinary application connections do not need them.

Isolation starts with ownership and access permissions. It does not require separate database servers or products. Decide on physical separation later according to performance, operational, and security needs.

🔎 Querying Complete Orders After Separating Data

Suppose an order details page needs:

Page fieldSourceReason
Order ID and amountOrdersNative order data
Current user nicknameUsersNicknames can change anytime
Product name and unit price at purchaseSnapshot stored by ordersHistorical orders must not change when products are repriced
Current available stockInventoryOnly inventory owns current stock

A shared-database system might use a JOIN. Orders should not now connect directly to user or inventory databases merely to assemble a page.

Option 1: Fetch and combine on demand

For the current nickname, the BFF can call orders and users, then combine the responses:

courseComponents.mermaid.loading

Data comes from its authoritative service without copying nicknames. The cost is another dependency during queries: slow user responses can delay the page. Earlier courses covered BFF aggregation code, so we will not repeat it.

Option 2: Save a business snapshot at purchase

Suppose the unit price is 99.00 yuan at purchase and becomes 109.00 a month later. Historical orders must retain the original transaction price.

Save confirmed prices and product names in order items when creating the order:

{
    "orderId": "o-100",
    "items": [
        { "sku": "A", "name": "Insulated cup", "unitPrice": 99, "quantity": 2 }
    ],
    "totalAmount": 198
}

unitPrice is the price snapshot confirmed at purchase. Do not query the current price whenever displaying history. Trusted server-side rules must determine the price during order creation, rather than accepting arbitrary client prices.

A snapshot records a fact at a business moment. Future price changes should not rewrite historical orders.


🔄 Maintaining Read-Only Copies for Frequent Queries

If a service frequently needs another service's data and remote requests are costly, consider a local read-only copy for queries.

For example, an order query page may show the current nickname while tolerating a few seconds of delay. Users publishes profile changes, and the order-side query data updates:

courseComponents.mermaid.loading

Suppose the nickname changes from “Alex” to “Sam”:

  1. Users has saved “Sam” and is the authoritative source.
  2. Before the notification is processed, the order-side copy may still say “Alex”.
  3. After processing, the copy becomes “Sam”.

Thus, a read-only copy can temporarily differ from authoritative data. Business requirements determine whether the delay is acceptable. Nickname display often tolerates it; reservation success cannot rely solely on a potentially stale copy.

Distinguish these two ways of keeping extra data:

ApproachPurposeUpdates with source data?
Historical snapshotPreserve facts established at purchaseUsually unaffected by current changes
Read-only copyReduce frequent cross-service query costsUpdated through events or synchronization, possibly with delay
A read-only copy does not solve reliable synchronization. Missing, duplicate, and out-of-order events require further design. Here, understand why data is copied, acceptable delay, and who owns authoritative data.

🛠 Safely Reserving Stock Inside Inventory

Owning data also means enforcing its rules. Suppose A has 5 available units and none reserved:

skuavailablereserved
A50

For an order requesting 2 units, inventory can execute a conditional update:

UPDATE stock
SET available = available - 2,
    reserved = reserved + 2
WHERE sku = 'A' AND available >= 2;

WHERE available >= 2 permits the update only when at least 2 units are available. If one row updates successfully, stock becomes:

skuavailablereserved
A32

MySQL's affected-row count indicates whether the update succeeded:

SELECT ROW_COUNT();

A result of 0 could mean the SKU is missing or stock is insufficient. Inventory must distinguish these and return an appropriate outcome. With sku as a unique key, the conditional update prevents concurrent requests from making available stock negative.

However, one UPDATE is not a complete reservation implementation. Real operations need a reservation ID, duplicate-request handling, and release after payment failure. These involve local transactions and cross-service coordination, discussed in business events and distributed transactions.

The key conclusion is: orders requests the reservation; inventory validates and changes stock. One atomic inventory update does not guarantee successful order creation.


❓ Knowledge Check

Q1: Do four services require four MySQL servers?

No. This project can share one MySQL instance with separate databases and account permissions. Physical separation can follow future requirements.

Q2: Why not let orders JOIN the user database directly?

That couples orders to user schemas and permissions. User schema changes could break orders. Prefer public APIs for current user information, evaluating read-only copies when concrete performance needs justify them.

Q3: Why not always fetch the latest price for an order?

Historical orders record completed transactions. Current prices can change without changing past transaction amounts.


🧪 Exercise

Design sources for an order details page showing order ID, current nickname, purchase unit price, and current available stock.

  1. Identify the authoritative service for each field.
  2. Decide which fields need historical snapshots and which need on-demand queries.
  3. If nicknames can lag by up to 5 seconds, explain whether a read-only copy works and what happens before updates arrive.
  4. Explain why orders must not update inventory tables directly.

Acceptance criteria: Identify all four data sources, distinguish snapshots from copies, avoid direct cross-service database writes, and explain why only inventory modifies stock.


🎉 Congratulations on completing this article! You can now assign data ownership and choose suitable data access approaches for cross-service queries.