Real-Time Inventory and Dynamic Pricing for E-Commerce with Streaming SQL

Real-Time Inventory and Dynamic Pricing for E-Commerce with Streaming SQL

·

Updated

·

12 min read

Real-time inventory and dynamic pricing for e-commerce means treating every order, cancellation, return, warehouse receipt, and competitor price change as an event that immediately updates a live stock count, a live reorder signal, and a live price recommendation. This guide builds all three on RisingWave, a PostgreSQL-compatible streaming database, with SQL materialized views and no custom pipeline code.

Why Batch Inventory and Scheduled Repricing Fail

An e-commerce operation with 50,000 SKUs that reconciles inventory hourly can oversell a popular product hundreds of times during a single flash sale. The batch job catches up at the top of the hour. By then the damage is customer service calls, refunds, and a reputation hit.

The root cause is architectural. Batch systems treat inventory as a state to be periodically recalculated rather than a value that changes incrementally with each event. The same flaw affects repricing: a scheduler, a Python script, and a chain of API calls run every few hours, so your price position is always a few cycles behind the competitor who undercut you at 2 AM.

The usual workarounds each solve part of the problem:

  • Polling the transactional database adds load to your primary store and still lags by the polling interval.
  • Redis counters handle increment and decrement but break down when you need to join stock with product data, warehouse locations, or reservation holds, and they are hard to audit.
  • Warehouse plus dbt keeps analytics fresh to the minute at best. Blocking a checkout on a warehouse query is not an option.
  • Rule engine platforms for pricing poll near real time but lock pricing logic in a vendor DSL.

What you need is a system that consumes event streams incrementally and maintains current state as a queryable, always-fresh view. That is what a streaming database does.

Architecture: Event Streams In, Materialized Views Out

The architecture has three layers and no scheduled jobs:

  1. Event ingestion. Orders, cancellations, returns, warehouse receipts, reservations, purchases, and competitor price observations publish to Kafka as they occur. Pricing rules live in a table that RisingWave can load from PostgreSQL through CDC.
  2. Streaming SQL processing. RisingWave consumes the topics as sources and maintains materialized views for live stock, sellable stock after holds, demand velocity, days of cover, reorder status, and recommended price.
  3. Serving. Your checkout service, replenishment tool, and pricing service query the views over the PostgreSQL wire protocol or receive changes through Kafka and JDBC sinks.

RisingWave is open source under Apache 2.0, written in Rust, and checkpoints state to S3, so the views survive restarts and the Kafka log remains the audit trail and the disaster recovery path.

Event Sources

Four topics carry inventory movements. Keeping them separate preserves the semantics of each event type, which matters for auditing and for the reservation logic later:

CREATE SOURCE orders_source (
    order_id      VARCHAR,
    product_id    VARCHAR,
    warehouse_id  VARCHAR,
    quantity      INT,
    unit_price    NUMERIC,
    event_time    TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'orders',
    properties.bootstrap.server = 'kafka:9092',
    scan.startup.mode = 'latest'
) FORMAT PLAIN ENCODE JSON;

CREATE SOURCE cancellations_source (
    order_id      VARCHAR,
    product_id    VARCHAR,
    warehouse_id  VARCHAR,
    quantity      INT,
    event_time    TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'order_cancellations',
    properties.bootstrap.server = 'kafka:9092',
    scan.startup.mode = 'latest'
) FORMAT PLAIN ENCODE JSON;

CREATE SOURCE returns_source (
    return_id     VARCHAR,
    product_id    VARCHAR,
    warehouse_id  VARCHAR,
    quantity      INT,
    event_time    TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'returns',
    properties.bootstrap.server = 'kafka:9092',
    scan.startup.mode = 'latest'
) FORMAT PLAIN ENCODE JSON;

CREATE SOURCE receipts_source (
    receipt_id    VARCHAR,
    product_id    VARCHAR,
    warehouse_id  VARCHAR,
    quantity      INT,
    event_time    TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'warehouse_receipts',
    properties.bootstrap.server = 'kafka:9092',
    scan.startup.mode = 'latest'
) FORMAT PLAIN ENCODE JSON;

Reservations model the hold placed on stock while a customer completes payment:

CREATE SOURCE reservations_source (
    reservation_id  VARCHAR,
    product_id      VARCHAR,
    warehouse_id    VARCHAR,
    quantity        INT,
    status          VARCHAR,     -- 'held' or 'released'
    event_time      TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'reservations',
    properties.bootstrap.server = 'kafka:9092',
    scan.startup.mode = 'latest'
) FORMAT PLAIN ENCODE JSON;

Competitor prices arrive from a price intelligence feed, and pricing constraints live in a table:

CREATE SOURCE competitor_prices (
    feed_id           VARCHAR,
    product_id        VARCHAR,
    competitor_name   VARCHAR,
    competitor_price  NUMERIC,
    currency          VARCHAR,
    observed_at       TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'competitor_price_feed',
    properties.bootstrap.server = 'kafka:9092',
    scan.startup.mode = 'latest'
) FORMAT PLAIN ENCODE JSON;

CREATE TABLE pricing_rules (
    product_id      VARCHAR PRIMARY KEY,
    category_id     VARCHAR,
    floor_price     NUMERIC,
    ceiling_price   NUMERIC,
    target_margin   NUMERIC,     -- decimal, 0.30 for 30%
    cost_price      NUMERIC,
    lead_time_days  INT
);

Live Inventory from Four Event Streams

Combine the movement streams into one signed delta stream and sum it per product and warehouse. Every arriving event adjusts only the affected row:

CREATE MATERIALIZED VIEW live_inventory AS
WITH inventory_events AS (
    SELECT product_id, warehouse_id, -quantity AS quantity_delta, event_time FROM orders_source
    UNION ALL
    SELECT product_id, warehouse_id,  quantity AS quantity_delta, event_time FROM cancellations_source
    UNION ALL
    SELECT product_id, warehouse_id,  quantity AS quantity_delta, event_time FROM returns_source
    UNION ALL
    SELECT product_id, warehouse_id,  quantity AS quantity_delta, event_time FROM receipts_source
)
SELECT
    product_id,
    warehouse_id,
    SUM(quantity_delta)   AS available_quantity,
    MAX(event_time)       AS last_updated_at
FROM inventory_events
GROUP BY product_id, warehouse_id;

Real checkouts hold stock before payment completes. Subtracting outstanding holds gives the number your storefront should actually display:

CREATE MATERIALIZED VIEW live_inventory_with_holds AS
SELECT
    li.product_id,
    li.warehouse_id,
    li.available_quantity,
    COALESCE(r.held_quantity, 0)                            AS held_quantity,
    li.available_quantity - COALESCE(r.held_quantity, 0)   AS sellable_quantity,
    li.last_updated_at
FROM live_inventory li
LEFT JOIN (
    SELECT
        product_id,
        warehouse_id,
        SUM(CASE WHEN status = 'held' THEN quantity
                 WHEN status = 'released' THEN -quantity
                 ELSE 0 END) AS held_quantity
    FROM reservations_source
    GROUP BY product_id, warehouse_id
) r ON li.product_id = r.product_id AND li.warehouse_id = r.warehouse_id;

Your application queries this exactly as it would a PostgreSQL table, so the existing ORM and connection pool work unchanged:

-- Gate checkout on sellable stock
SELECT sellable_quantity
FROM live_inventory_with_holds
WHERE product_id = 'SKU-98231' AND warehouse_id = 'WH-EAST-01';

-- Products out of stock across every warehouse
SELECT product_id, SUM(sellable_quantity) AS total_sellable
FROM live_inventory_with_holds
GROUP BY product_id
HAVING SUM(sellable_quantity) <= 0;

Two operational notes. Kafka plus RisingWave is at-least-once by default, so producers should include an idempotency key such as order_id, and you can deduplicate in a view with SELECT DISTINCT ON (order_id) before the sum if duplicates are possible. Because Kafka retains the event log, you can rebuild live_inventory from any offset, which doubles as your audit trail.

Demand Velocity, Days of Cover, and Reorder Points

Inventory is the most expensive asset most e-commerce businesses carry. A product featured in a 9 AM newsletter can sell through its safety stock by 11 AM, and a nightly replenishment job will not notice until tonight. Streaming the same order events into a demand velocity view closes that loop.

A seven-day trailing velocity sets the baseline, and a two-hour hopping window captures what is happening right now:

CREATE MATERIALIZED VIEW demand_velocity_7d AS
SELECT
    product_id,
    SUM(quantity)                 AS units_sold_7d,
    SUM(quantity) / 7.0           AS units_per_day_7d,
    COUNT(DISTINCT order_id)      AS orders_7d
FROM orders_source
WHERE event_time >= NOW() - INTERVAL '7 DAYS'
GROUP BY product_id;

CREATE MATERIALIZED VIEW demand_velocity_2h AS
SELECT
    product_id,
    window_start,
    window_end,
    SUM(quantity)                 AS units_sold_2h,
    COUNT(DISTINCT order_id)      AS orders_2h
FROM HOP(orders_source, event_time, INTERVAL '15 MINUTES', INTERVAL '2 HOURS')
GROUP BY product_id, window_start, window_end;

Joining stock on hand with velocity and the product's lead time produces days of cover, a recommended safety stock, a reorder point, and a status label the replenishment team can act on:

CREATE MATERIALIZED VIEW inventory_health AS
SELECT
    li.product_id,
    li.warehouse_id,
    li.sellable_quantity                                         AS units_on_hand,
    COALESCE(dv.units_per_day_7d, 0)                             AS demand_rate_per_day,
    CASE WHEN COALESCE(dv.units_per_day_7d, 0) > 0
         THEN li.sellable_quantity / dv.units_per_day_7d END     AS days_of_cover,
    -- Safety stock: 1.5x expected demand over the lead time
    COALESCE(dv.units_per_day_7d, 0) * pr.lead_time_days * 1.5   AS safety_stock,
    -- Reorder point: lead-time demand plus safety stock
    COALESCE(dv.units_per_day_7d, 0) * pr.lead_time_days * 2.5   AS reorder_point,
    CASE
        WHEN li.sellable_quantity <= 0 THEN 'stockout'
        WHEN li.sellable_quantity <= COALESCE(dv.units_per_day_7d, 0) * pr.lead_time_days * 1.5 THEN 'below_safety_stock'
        WHEN li.sellable_quantity <= COALESCE(dv.units_per_day_7d, 0) * pr.lead_time_days * 2.5 THEN 'reorder_now'
        ELSE 'healthy'
    END AS inventory_status
FROM live_inventory_with_holds li
JOIN pricing_rules pr USING (product_id)
LEFT JOIN demand_velocity_7d dv USING (product_id);

Because the view is incremental, a flash sale that pushes demand to ten times normal moves a SKU from healthy to reorder_now within minutes of the surge starting, not the next morning.

Dynamic Pricing from Competitor, Demand, and Inventory Signals

Dynamic pricing means charging more when demand is high and stock is scarce, and staying competitive when you have inventory to move. The difficulty is that the signals live in different systems and change at different rates: competitor feeds every 15 minutes, inventory with every order, demand as a rolling calculation. A streaming join keeps all three current at once.

Start with your price position against the market:

CREATE MATERIALIZED VIEW competitor_min_price AS
SELECT
    product_id,
    MIN(competitor_price)             AS min_competitor_price,
    MAX(competitor_price)             AS max_competitor_price,
    AVG(competitor_price)             AS avg_competitor_price,
    COUNT(DISTINCT competitor_name)   AS competitor_count,
    MAX(observed_at)                  AS last_updated_at
FROM competitor_prices
GROUP BY product_id;

Then join competitor position, two-hour demand, and sellable stock with the pricing rules. Demand and scarcity each contribute a multiplier, and the floor, ceiling, and margin constraints are enforced in the same expression:

CREATE MATERIALIZED VIEW total_sellable AS
SELECT product_id, SUM(sellable_quantity) AS available_quantity
FROM live_inventory_with_holds
GROUP BY product_id;

CREATE MATERIALIZED VIEW price_recommendations AS
WITH signals AS (
    SELECT
        pr.product_id,
        pr.floor_price,
        pr.ceiling_price,
        pr.cost_price,
        pr.target_margin,
        COALESCE(cmp.min_competitor_price, pr.ceiling_price)  AS min_competitor_price,
        COALESCE(dv.units_sold_2h, 0)                         AS units_sold_2h,
        COALESCE(inv.available_quantity, 0)                   AS available_quantity
    FROM pricing_rules pr
    LEFT JOIN competitor_min_price cmp ON pr.product_id = cmp.product_id
    LEFT JOIN demand_velocity_2h dv    ON pr.product_id = dv.product_id
                                      AND dv.window_end > NOW() - INTERVAL '15 MINUTES'
    LEFT JOIN total_sellable inv       ON pr.product_id = inv.product_id
),
scored AS (
    SELECT
        *,
        CASE
            WHEN units_sold_2h >= 50 THEN 1.10
            WHEN units_sold_2h >= 20 THEN 1.05
            WHEN units_sold_2h >= 5  THEN 1.00
            WHEN units_sold_2h >= 1  THEN 0.97
            ELSE 0.95
        END AS demand_multiplier,
        CASE
            WHEN available_quantity <= 5   THEN 1.08   -- scarcity premium
            WHEN available_quantity <= 20  THEN 1.03
            WHEN available_quantity >= 200 THEN 0.95   -- excess stock, move it
            ELSE 1.00
        END AS inventory_multiplier
    FROM signals
)
SELECT
    product_id,
    floor_price,
    ceiling_price,
    min_competitor_price,
    units_sold_2h,
    available_quantity,
    GREATEST(
        floor_price,
        cost_price * (1 + target_margin),                      -- margin floor
        LEAST(
            ceiling_price,
            ROUND(min_competitor_price * 0.99 * demand_multiplier * inventory_multiplier, 2)
        )
    ) AS recommended_price,
    NOW() AS computed_at
FROM scored;

When a competitor cuts price overnight, recommended_price moves within seconds. When a flash sale drives a SKU down to five units, the scarcity premium applies automatically. The GREATEST(floor, margin floor, LEAST(ceiling, ...)) pattern guarantees no recommendation ever drops below cost plus target margin or above the configured ceiling, even if the competitor feed collapses.

Because the strategy is SQL, running two strategies side by side for an A/B test is a second view rather than a deployment. Strategy A can be pure competitor parity and strategy B demand-adjusted, with products or traffic segments assigned to each and conversion compared in your analytics layer.

Serving Inventory and Price Changes

Three delivery patterns cover most deployments.

Direct queries. Checkout and product pages read live_inventory_with_holds directly. RisingWave serves point lookups on materialized views with low latency, and the PostgreSQL protocol means no new client library.

Upsert sink to the replenishment database. Purchasing tools usually read from PostgreSQL, so keep a table there current:

CREATE SINK inventory_health_sink FROM inventory_health
WITH (
    connector   = 'jdbc',
    jdbc.url    = 'jdbc:postgresql://wms-db:5432/inventory',
    table.name  = 'inventory_health_live',
    type        = 'upsert',
    primary_key = 'product_id,warehouse_id'
);

Kafka sinks for alerts and price changes. Low-stock alerts go to the merchandising team, and price changes go to a consumer that applies them through the storefront API. The Kafka topic doubles as a complete audit trail of every price the engine ever recommended, which helps with reconciliation and compliance reviews:

CREATE SINK low_stock_alerts
FROM (SELECT * FROM inventory_health WHERE inventory_status IN ('stockout', 'below_safety_stock'))
WITH (connector = 'kafka', topic = 'low_stock_alerts', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;

CREATE SINK price_change_events
FROM (SELECT product_id, recommended_price, computed_at FROM price_recommendations)
WITH (connector = 'kafka', topic = 'price_updates', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;

Alternatively, a pricing service can poll price_recommendations every few seconds and apply changes itself, trading a small lag for simpler control over when prices move.

Batch vs Streaming for Inventory and Pricing

DimensionHourly batch jobRedis countersScheduled repricing scriptStreaming SQL (RisingWave)
Stock freshnessUp to one hour staleSecondsNot applicableSeconds
Reservation holdsSeparate systemManual invalidationNot applicableOne LEFT JOIN
Reorder signalsNightlyNot supportedNot applicableContinuous, per SKU
Competitor responseNot applicableNot applicableCron intervalSeconds after the feed event
Floor and margin enforcementCustom codeCustom codeCustom codeSQL expression
Audit trailJob logsNoneLogsKafka event log, replayable
Oversell during a flash saleLikelyPossible under race conditionsNot applicableSellable count updated per event

Frequently Asked Questions

Can I stream inventory tables directly from my database instead of publishing events? Yes. RisingWave has native CDC connectors for PostgreSQL and MySQL. Point a CDC source at your orders and stock tables and the views above work the same way, with each row change arriving as an event.

How do I prevent duplicate events from double-counting stock? Include an idempotency key on every event and deduplicate with SELECT DISTINCT ON (order_id) in a view before the aggregation. Combined with Kafka's retention, this gives you exactly-once results from at-least-once delivery.

How often does the price recommendation change? It changes whenever an input changes: a competitor observation, an order, a receipt, or a rules update. If you want to limit how frequently prices move on the storefront, apply changes through a consumer that batches updates or only applies deltas above a threshold.

Can one view serve multiple warehouses and regions? Yes. Every view groups by warehouse_id where it matters, and total_sellable rolls up across warehouses for pricing. Add a region column to the pricing rules table if you price differently by market.

What happens on restart? RisingWave checkpoints view state and Kafka offsets to S3-compatible storage. After a restart it resumes from the last checkpoint, so inventory counts are not recomputed from scratch and no events are lost.

The engine for real-time streaming data.
Analyze, search, and decide.
GitHubXLinkedInSlackYouTube
Sign up for our to stay updated.