Price a basket with CoAkka Runtime

Price a basket in one Node.js process, then move pricing to Python and compare the results. Run every step on your own machine and open the basket at a local address.

Set up the project

Install Node.js 22 or later and npm on your machine. Use a supported package platform. Use an existing Samples checkout or clone one. The project pins the Node.js and Python packages to 3.3.2. Install the Python package when you move pricing to its own process.

Clone Samples
git clone https://github.com/phuong-tran/coakka-samples.git
cd coakka-samples
Install Node.js packages from the Samples root
cd coakka-runtime/scenarios/order-quote-node-python
npm ci

Price a basket in one Node.js process

In Embedded mode, Node.js sends the request and handles samples.order.quote in the same process. Try cart.json and a basket of 4 teas to get two results you can compare. This example uses those two valid baskets. The application's pricing handler sets prices and shipping.

Node.js source for the Embedded exercise

Save the code as embedded-quote.mjs in the project directory, next to cart.json and package.json.

embedded-quote.mjs
import { Buffer } from "node:buffer";

import { RuntimeHost, localRoute } from "coakka-runtime-node";

import { readCart } from "./client.mjs";
import { TARGET } from "./quote-client.mjs";

// Prices for the two teaching carts, in whole cents.
const prices = new Map([["tea", 1250], ["coffee", 1800]]);

function quote(payload) {
  const { cartId, items } = JSON.parse(Buffer.from(payload).toString("utf8"));
  const lines = items.map(({ sku, quantity }) => {
    const unitPriceCents = prices.get(sku);
    return { sku, quantity, unitPriceCents, lineTotalCents: unitPriceCents * quantity };
  });
  const subtotalCents = lines.reduce((total, line) => total + line.lineTotalCents, 0);
  const shippingCents = subtotalCents >= 5000 ? 0 : 500;
  return Buffer.from(JSON.stringify({
    status: "quoted",
    cartId,
    currency: "USD",
    items: lines,
    subtotalCents,
    shippingCents,
    totalCents: subtotalCents + shippingCents,
  }));
}

const startingCart = await readCart(new URL("./cart.json", import.meta.url));
const freeShippingCart = { ...startingCart, items: [{ sku: "tea", quantity: 4 }] };

// Omitting network configuration keeps the handler in this process.
const runtime = RuntimeHost.start({
  systemName: "order-quote-demo",
  nodeId: "embedded-checkout",
  routes: [localRoute(TARGET)],
});

try {
  runtime.registerPayloadHandler(TARGET, quote);
  for (const cart of [startingCart, freeShippingCart]) {
    const payload = Buffer.from(JSON.stringify(cart));
    const bytes = await runtime.askPayload("checkout", TARGET, payload, 2000);
    const reply = JSON.parse(Buffer.from(bytes).toString("utf8"));
    const shipping = (reply.shippingCents / 100).toFixed(2);
    const total = (reply.totalCents / 100).toFixed(2);
    console.log(`Shipping USD ${shipping}, total USD ${total}`);
  }
} finally {
  await runtime.close();
}

Run this from the project directory.

Terminal
node embedded-quote.mjs
Shipping USD 5.00, total USD 48.00
Shipping USD 0.00, total USD 50.00

The script closes CoAkka Runtime and exits after printing both quotes. Continue with Python pricing.

Move pricing to Python

When pricing needs a Python library or needs to run independently, move the handler to a Python process. The browser sends the basket to Node.js. Node.js still calls samples.order.quote with the same basket structure. Its route now points to Python on the same machine.

Install standard CPython 3.11 or later. From the project directory, choose the Python package setup for your operating system.

macOS / Linux
Install Python on macOS or Linux
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
Windows PowerShell
Install Python on Windows
py -3.11 -m venv .venv
.venv\Scripts\python.exe -m pip install -r requirements.txt

Start Python from the project directory in Terminal A and keep it open.

macOS / Linux
Start Python on macOS or Linux
.venv/bin/python pricing_service.py
Windows PowerShell
Start Python on Windows
.venv\Scripts\python.exe pricing_service.py
Pricing service ready at 127.0.0.1:19360

Open Terminal B in the same project directory and start the Node.js web app.

Start the basket page
npm run web

Open the address Terminal B prints, normally 127.0.0.1:8080.

Change the basket and check the result

Click Get quote with 2 teas and 1 coffee. The result matches the Embedded exercise. Python returns a USD 43.00 subtotal and USD 5.00 shipping, for USD 48.00.

Change the basket to 4 teas and 0 coffees. Request another quote to see USD 50.00 total and Free shipping. An edit marks the previous quote out of date. Reset example restores the starting basket.

The basket and prices are sample data. View the basket screenshot.

Try stopping Python

  1. Stop Python with Enter or Ctrl+C in Terminal A. Keep Node.js and the basket page running.
  2. Click Get quote. The page reports Quote unavailable. A rejected basket is a business reply sent after Python processed the request.
  3. Restart Python. Wait for the ready message and request another quote from the same page. The starting basket returns USD 48.00 again.
  4. When finished, stop Node.js with Ctrl+C in Terminal B, then stop Python.

If a port is busy, use the port options in the project troubleshooting guide. The demo listens on loopback.

Run the project tests

After stopping the two manual demo processes, run this from the project directory.

Check pricing, failures and shutdown
npm test

View the project source · Learn with the smaller Runtime example.

Apply the same approach in your app

Keep pricing in one process as long as it meets your needs. When you split it out, keep the basket and quote contract. Check the expected results, what happens when Python stops, and how requests recover when it is back.