Skip to content

Idempotent VM orders with a client order ID - #448

Open
douglaz wants to merge 1 commit into
LNVPS:masterfrom
douglaz:vm-order-id
Open

douglaz wants to merge 1 commit into
LNVPS:masterfrom
douglaz:vm-order-id

Conversation

@douglaz

@douglaz douglaz commented Nov 28, 2026

Copy link
Copy Markdown

Problem

A client that sends POST /api/v1/vm or POST /api/v1/vm/custom-template and loses the reply (a dropped connection, a timeout, a proxy error) cannot tell whether a machine was ordered. Today the only way to find out is to list the account's VMs and guess which one is new, and a plain retry orders a second machine with its own subscription, which the client may then go on to pay for.

What this changes

  • Both create routes accept an optional order_id in the JSON body. The client generates it, a canonical lowercase UUIDv4, and keeps it with the order it is about to send.
  • The first request with a given account and ID claims the ID in a new table and creates the order in the same database transaction: the claim, the subscription, its line item, the VM and, on the custom route, the custom template. If any step before the commit fails, the claim and the staged order rows are rolled back and the ID stays free (writes made outside the order, such as account creation, geolocation capture and any sanctions screening record, are kept) for a retry. Once the order is committed, the reply is rendered from the database; if that rendering fails the client gets a server error, and a retry with the same ID returns the committed order. A client should therefore keep the ID and retry with it after any uncertain reply.
  • A repeat of the same order under the same account and ID returns the original VM instead of creating another. The comparison uses a SHA-256 digest of the typed order (route included, order_id excluded), so JSON key order and whitespace do not matter. On the custom route the CPU selectors are normalised the way placement reads them, and the feature list is compared as a set.
  • GET /api/v1/vm/templates reports honours_order_id, so a client can check before relying on the ID, and the catalogue reply is now sent with Cache-Control: no-store.
  • Requests without order_id run the existing handlers unchanged.
  • API_DOCUMENTATION.md and API_CHANGELOG.md describe the field, the replies and the catalogue flag.

API

Request field, on CreateVmRequest and CustomVmOrder:

order_id?: string; // canonical lowercase UUIDv4, generated by the client

Any other form (upper case, no hyphens, another UUID version, null) is rejected when the body is parsed, before any order work.

Authentication: with NIP-98, a request carrying order_id must include the payload tag, which the existing middleware checks against the body. Without the tag the request gets 401 "A signed payload is required for order_id". A retry uses a fresh auth event over the same body. Session and API token bearer authentication are unchanged.

Replies, for the same authenticated account and order_id:

Request Reply
First request The normal create reply (VmStatus)
Exact repeat on the same route The original VM and subscription, rendered as a create reply from current data. No new rows. The repeat is answered before the account order limit, geolocation, screening and pricing run.
Changed order fields, or the same ID on the other create route 409 "order_id has already been used"
Exact repeat after the VM was deleted, transferred or unlinked from its subscription 404. The ID stays bound to that order.

An expired VM that still exists on the account is returned with its current status. IDs are scoped per account: two accounts can use the same value independently.

Catalogue, GET /api/v1/vm/templates:

honours_order_id?: boolean;

true means both create routes honour the contract above. A missing field or false means they do not, which is what clients see from older versions. This version always reports true; the value is a constant in the catalogue handler, not detected at run time. It is only correct while every process that can receive create requests runs this version, so during a rolling upgrade the catalogue should not be served by upgraded processes while create requests can still reach older ones. An older process ignores order_id and creates a second order. The reply carries Cache-Control: no-store so that a saved true is not reused; clients are asked to read the flag fresh before the first send and again before any repeat, and to repeat only when both reads returned true.

Compatibility

  • A client that sends no order_id sees no change on either create route.
  • The catalogue gains an optional field that existing clients can ignore. Its reply is now no-store for every client, so caches in front of the API stop caching it.
  • Keyed creates need the migration below, applied before keyed traffic reaches the new version. The API applies migrations at startup.

Database

New migration lnvps_db/migrations/20261201000300_vm_order_identity.sql, additive only:

CREATE TABLE vm_order_identity (
    user_id BIGINT UNSIGNED NOT NULL,
    order_id BINARY(16) NOT NULL,
    request_digest BINARY(32) NOT NULL,
    vm_id BIGINT UNSIGNED NULL,
    subscription_id BIGINT UNSIGNED NULL,
    PRIMARY KEY (user_id, order_id),
    CHECK ((vm_id IS NULL) = (subscription_id IS NULL))
) ENGINE=InnoDB;

No foreign keys and no backfill; existing orders have no rows. The primary key decides between concurrent claims of the same ID: a second claim waits on the first transaction, then reads its committed result, or takes the claim itself if the first rolled back. The migration's version follows the three 20261201… migrations already on the base.

Each API process also opens a second, lazily connected MySQL pool of up to 8 connections. It is used only for keyed orders: the claim transaction, held from the claim to the commit, and the locked read that renders a keyed reply. Those cannot starve the main pool, but they share these 8 connections (see Known limits).

On hourly plans the keyed path runs the existing credit quote before commit, with the staged rows visible to the quote's own reads, and refuses an unfunded order with the existing error message without committing anything. The same ID can be used again after the account is funded. The unkeyed paths keep their current behaviour.

Testing

  • Workspace test suite, all crates except the end-to-end crate, single-threaded, against a throwaway MariaDB 12.3.3 with LNVPS_TEST_DATABASE_URL set: 2,972 passed, 0 failed, 25 ignored across 56 test harness results. This run was made before the catalogue flag was added.

  • After the catalogue flag was added, the three tests in api::routes::tests::orders were run against the same kind of database: 3 passed, 0 failed. The rest of the suite was not run again after that.

  • The new tests go through the production router and signed request middleware on both routes. They cover replay after a discarded reply through a fresh router, 409 for changed fields and for the other route, the same ID under two accounts, independent orders without an ID, rollback of an unfunded hourly order on both routes followed by a funded retry and a replay, and the catalogue flag with its cache header.

  • An earlier signed HTTP run (before the tests and the catalogue flag were added) against two API processes sharing one migrated MariaDB, on loopback with no workers and no payment or hypervisor backends. Two processes received the same keyed order at the same time, and both returned the same VM after the second claim was observed waiting on the first. The run also covered a sequential retry with an equivalent CPU architecture spelling, 409s, a reply discarded after commit and replayed after restarting both processes, a second account using the same ID, 401 for a signature over changed body bytes, and two unkeyed orders on each route creating two VMs. It added no payments.

  • A second signed HTTP run on the finished change, through the production routes on an isolated setup with no external connections. On both routes the catalogue reported true before the create and again before the repeat, the create reply was discarded unread after the order was committed, and the repeat returned the same VM and subscription, leaving one order per account. Unkeyed orders on both routes created separate orders. It added no payments.

  • On a private instance running these changes, a client's first create reply was lost and the client sent the same create again with the same order ID and body. Both requests were answered with the same machine, and the order had one invoice request and one settled payment.

  • The branch was then rebased onto the current master without conflicts and compile-checked (the lnvps_api library, binaries and tests). The tests were not run again after the rebase.

Known limits

  • The new database tests return early, and pass, when LNVPS_TEST_DATABASE_URL is not set, as the existing database tests do. Without a database they check nothing.
  • Overlapping claims of the same ID and a process restart are covered only by the external HTTP run above, not by the test suite. The suite also does not check the credit balance or reservations right after a refused hourly order, or that a replay leaves exactly one VM creation history entry. No test holds the hourly quote open to check that the staged rows stay visible only to that request's own reads: that visibility is a per-poll, thread-local overlay on seven read methods of the MySQL backend, and a read added to the quote path later would not see the staged rows unless it is added to the overlay.
  • honours_order_id is a constant. It cannot see a mixed-version deployment, and a database backend other than MySQL (the in-process mock, for example) refuses keyed orders while the catalogue still reports true.
  • Each API process holds at most 8 order-pool connections at once: every new keyed create holds an order-pool connection from its claim until its commit, through the order limit, screening, placement and the hourly quote, and every keyed reply, replays included, takes one for its locked read. Further claims and locked reads queue for a connection, and waiters on the same ID hold theirs while they wait on the first claim. There is no separate bound, and how unrelated accounts fare under such load was not measured. Unkeyed orders do not use this pool.
  • On the custom route, an unfunded hourly order is refused before commit when it carries an ID, while the unkeyed custom route keeps its current behaviour, which has no such early check. The two paths therefore differ for unfunded hourly custom orders.
  • The VM creation history entry and the suspicious-order alert run after commit, best effort. They are lost if the process stops right after commit, and a repeat does not replay them. Geolocation capture, screening and its notification, and the account order limit run before commit, so they can run again when an attempt rolls back and is retried.
  • A replay renders the VM the way a fresh create reply does. It does not add the live running state that the VM status route reports.
  • There is no route to look up an order by its ID. A client that loses the ID cannot recover the order through this mechanism.
  • A rolled-back attempt can leave gaps in the auto-increment IDs.

Accept an optional order_id, a canonical lowercase UUIDv4 generated by
the client, on POST /api/v1/vm and POST /api/v1/vm/custom-template. The
first request for an account and ID claims it in the new
vm_order_identity table and creates the order in the same transaction.
An exact repeat returns the original VM and subscription, a changed
order or the other create route returns 409, and a repeat after the VM
is gone returns 404. NIP-98 requests with an order_id must carry a
payload tag. Requests without an order_id are unchanged.

On hourly plans the keyed path runs the existing credit quote before
commit and leaves nothing behind when it refuses.

Report honours_order_id on GET /api/v1/vm/templates and send the
catalogue with Cache-Control: no-store.

Needs migration 20261201000300_vm_order_identity.sql.
@douglaz
douglaz marked this pull request as ready for review November 28, 2026 23:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant