---
title: "SQLite retry creates duplicate orders"
category: "code"
id: 37ced06e-af49-4cf1-bd97-47c8eaff560a
canonical: https://solvedlist.com/solutions/sqlite-retry-creates-duplicate-orders
---

# SQLite retry creates duplicate orders

> Solution for idempotent order creation in SQLite with unique client-request key pairs and payload validation.

## Question

Python POST handler commits order to SQLite but response is lost. Retrying creates duplicate. How to return same order ID and reject key reuse with different payload?

## Solution

The first commit can succeed even when the client times out. Reuse one key for the same request. Scope it to the authenticated client and enforce uniqueness in SQLite. Initialize with db.executescript(SCHEMA) and use a dedicated transactional sqlite3 connection.

```python
SCHEMA = """
CREATE TABLE orders (
    id INTEGER PRIMARY KEY,
    client TEXT NOT NULL,
    request_key TEXT NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    UNIQUE (client, request_key)
);
"""


def create_order(db, client, key, quantity):
    with db:
        db.execute(
            """INSERT INTO orders (client, request_key, quantity)
               VALUES (?, ?, ?)
               ON CONFLICT (client, request_key) DO NOTHING""",
            (client, key, quantity),
        )
        order_id, saved_quantity = db.execute(
            """SELECT id, quantity FROM orders
               WHERE client = ? AND request_key = ?""",
            (client, key),
        ).fetchone()
        if saved_quantity != quantity:
            raise ValueError("idempotency key reused with different quantity")
        return order_id
```

The example compares quantity, its entire payload. For a larger request, compare a canonical fingerprint.

## Query directly via MCP

```text
POST https://solvedlist.com/mcp
Authorization: Bearer sl_live_…
Content-Type: application/json

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"solvedlist_lookup","arguments":{"question":"…"}}}
```

Create an API key without an account:

```bash
curl -sS -X POST https://solvedlist.com/api/v1/keys -H 'Content-Type: application/json' -d '{"note":"agent"}'
```

More for agents: https://solvedlist.com/llms.txt and https://solvedlist.com/openapi.json
