QA Interview Hub · Knowledge base · Quizzes · Українська

API › The most critical API bugs

Contract and performance: breaking change, 200 with an error, N+1

A breaking change is a contract change after which an old client breaks: a renamed or removed field, a changed type, a new required request field. It is caught before release by comparing specifications and by contract tests. An error in the body with status 200 is invisible to clients and monitoring, so the first assert is on status, and N+1 is found by measuring time and SQL queries at growing volume.

API · Typical bugs

The dashboard shows 100% success, yet clients complain about errors. What went wrong?

After a release the mobile app shows an empty phone number: the backend renamed phone to phoneNumber. Monitoring is cheerful because the error is returned as 200 OK with {"status":"error"}. And a list endpoint with 10 records is fast until a client with 100,000 shows up in production. What these bugs share: they do not break a single request in a test, they break the agreement with clients or the behaviour under volume.

Three cases: a breaking contract change, 200 with an error in the body, N+1 and unbounded requests.

How it works

The contract. A client writes code for the shape of the response: field names, types, allowed enum values, error codes. Anything that changes this shape so that old code stops working is a breaking change: renaming or removing a field, changing a type ("id": 5 became "id": "5"), a new required field in a request, a new enum value the client does not know, narrowing a range. Adding an optional field to a response is usually safe. Mobile apps do not update instantly, so old versions live for months.

The status. Clients, caches, gateways and monitoring work with the status code, not with the body. 200 means “success”, and retries, caches and metrics behave accordingly. An error in the body under that status is invisible to the whole infrastructure.

The volume. N+1 happens when for a list of N records there is 1 query for the list and one more per item (its author, its status). The number of SQL queries grows with the response, and so does the time.

A failure that is seen and one that is not

Typical

200 and status: error in the body

Monitoring counts a success, a cache may store the response, an automatic retry considers the request done.

Better

422 or 5xx and Problem Details

Metrics show a failure, the cache does not store it, the client sees the reason in a standard format.

Figure 1. Only the client reads the error body, while everyone reads the status. So the error belongs in the status.

Example: a breaking change

The change can be found before the release by comparing specifications. The oasdiff tool (an OpenAPI CLI) has a breaking command that is put into CI. Take flag names from its documentation:

# compare the specification of the release candidate with production
oasdiff breaking https://prod.example.test/openapi.yaml ./openapi-next.yaml

# the CI job fails on a breaking change
oasdiff breaking prod.yaml next.yaml --fail-on ERR

A specification may not match the code, so add a test against a live response that checks what the old client relies on: names, types, enums.

test('the old client contract of GET /v1/users/{id} still holds', async ({ request }) => {
  const user = await (await request.get('/v1/users/7')).json();

  expect(typeof user.id).toBe('number');          // not "7"
  expect(typeof user.phone).toBe('string');       // not renamed to phoneNumber
  expect(['active', 'blocked']).toContain(user.status); // no unknown enum value
});

The fix: return both fields for the migration period, add a version (/v2) and announce the support period of the old one. A contract test (consumer-driven, for example Pact) checks the consumers’ expectations in the provider’s CI before the release.

Example: 200 with an error

The error is visible only in a negative scenario: insufficient funds, invalid data, someone else’s resource. The response looks like this:

HTTP/1.1 200 OK
Content-Type: application/json

{ "status": "error", "message": "Insufficient funds" }

The test checks the status first, because clients may already parse the body (the fix will break them, so find the consumers). The body format is RFC 9457 Problem Details:

test('insufficient funds is an error status, not 200', async ({ request }) => {
  const res = await request.post('/v1/accounts/42/transfers', {
    headers: { 'Idempotency-Key': crypto.randomUUID() },
    data: { toAccount: 'UA21...', amountMinor: 99999999, currency: 'UAH' },
  });
  expect(res.status()).toBe(422); // checked first, the body second
  expect(res.headers()['content-type']).toContain('problem+json');
});

Example: N+1 and an unbounded request

A sign of N+1: time grows linearly with the response size. The test measures time for 10, 50 and 100 records (100 is the maximum limit here) and tries a very large limit. The number of SQL queries per API request is best seen in logs or APM, and it must not grow with the response size:

for (const size of [10, 50, 100]) {
  test('list time with ' + size + ' orders', async ({ request }) => {
    await seedOrders(size); // helper that creates data for one test user
    const t0 = performance.now();
    const res = await request.get('/v1/orders?limit=' + size);
    const ms = performance.now() - t0;
    expect(res.status()).toBe(200);
    console.log(size, 'rows:', Math.round(ms), 'ms'); // growth must be flat-ish
    expect(ms).toBeLessThan(1500);
  });
}

test('an absurd limit is capped or rejected', async ({ request }) => {
  const res = await request.get('/v1/orders?limit=100000');
  if (res.status() === 200) expect((await res.json()).items.length).toBeLessThanOrEqual(100);
  else expect(res.status()).toBe(400);
});

A list of N records with their authors

Typical

N+1

1 query for the list and N for the authors: 1001 calls for 1000 records.

Better

A join or batch loading

1-2 queries for the list and all authors at once. The count does not depend on N.

Figure 2. The difference is the number of database queries. It is what turns a fast endpoint into a slow one as data grows.

The fix: eager loading or a join, pagination with an upper bound on limit, an index for filters and sorting.

Limits and alternatives

  • Comparing specifications catches only what is described. An undocumented change (the type of a field in a real response) requires a test on live responses or schema validation.
  • A timing test on a shared stage is noisy. Take a rough threshold and repeat it, and leave exact numbers to a load test with percentiles.
  • Not every field removal is breaking: if a field is marked deprecated and has no consumers, it can be removed under the versioning policy. But that is a team decision, not a tester’s.
  • When changing 200 to 4xx, remember the clients that parse the body. Agree on the transition.

Common mistakes

  • Treating adding a field as safe in all cases. A client with strict schema validation may fail on an unknown field.
  • Checking only the body of a negative response. A 200 status covers up the error, so the first assert must be on the status.
  • Measuring time on a small set. N+1 shows up only as the volume grows.
  • Not trying a large limit. An unbounded request is a way to bring the service down with one call.
  • Looking only at the specification. The code may drift from it, so a live-response check is needed too.

Check yourself

A new release returns "id": "5" instead of "id": 5. Tests that check toBeTruthy() are green. Why is this a problem and how do you catch it?

Answer

The field type changed, which is a breaking change: a client that compares the id as a number or passes it on breaks. A weak check does not notice. I catch it with typeof user.id === "number", JSON Schema validation or a specification comparison in CI.

A list endpoint answers in 80 ms with 10 records and in 12 s with 10,000. What do you do?

Answer

I suspect N+1 or a missing index or pagination. I measure time for 10, 100, 1000, look at the number of SQL queries per API request and the response size, and try a large limit. The report: request, volume, time, number of database queries. The fix: a join or eager loading, a limit, an index.

In an interview. Junior: A breaking change is a response change that breaks an old client: a renamed field or a different type. An error inside a 200 is bad because the status says “success”. Middle/Senior: I catch a breaking change before release by comparing OpenAPI in CI and with contract tests on a live response, and fix it by adding a version and a migration period. I find an error in a 200 with negative scenarios and the status as the first assert. For N+1 I measure time on a growing volume and count SQL queries per API request, and I also cap the limit and add an index.

More articles in this chapter