Test that a database query is fast enough

Add a time budget to a SQL step of a zriz pipeline. The step fails when the query needs more milliseconds than your limit.

Lesson 12 of 12 · zz 0.9.0 or later · Updated · Plain text for agents: /learn/test-database-query-speed.md

The problem

A query is slow when an index is missing or a table grows. The result stays correct, so a test of the rows does not see it. The page that uses the query gets slow.

The test

The example is a shop API with a MySQL database. The query counts the rows of the table users. It must take under 50 ms.

Start from a project that zz init made: the quick start gives the commands. Add the database value and the database resource.

.zriz/environments/local.json:

{
  "values": {
    "TARGET_URL": "http://localhost:9080",
    "SHOP_DB": "user:pass@tcp(localhost:3306)/shop"
  },
  "sensitive": ["SHOP_DB"]
}

.zriz/resources/shopdb.json:

{
  "type": "sql",
  "connection": "${env.SHOP_DB}",
  "read-only": true,
  "actions": {
    "count-users": { "query": "SELECT COUNT(*) AS total FROM users" }
  }
}

.zriz/pipelines/query-is-fast.json:

{
  "description": "The user count takes under 50 ms",
  "steps": [
    {
      "call": "shopdb/count-users",
      "expect": [
        ["row-count", "==", 1],
        ["timing.target-ms", "<", 50]
      ]
    }
  ]
}

Run it

zz run query-is-fast
"status":"pass"

What it proves

Common mistake: A small test table is always fast. Use a database with data like production.

Next