Wiring in an AI service: working with a slow, uncertain boundary
A school management system needed to record attendance through face recognition. A camera takes a picture, an external AI service analyses it, the system marks the student.
At first glance that is a simple integration: send an image to an API, get a response, write it to the database.
In practice an AI service does not behave like an ordinary API. It differs in three ways, and each one shapes the architecture:
- It is slow. Responses take seconds, not milliseconds.
- It is unreliable. Sometimes it does not answer at all, or answers late.
- It is probabilistic. The result is not "yes" or "no" but a confidence level.
This article is about working with that kind of boundary.
First rule: do not wait synchronously
The most common mistake is making the AI call inside the request:
app.post('/attendance/scan', async (c) => {
const image = await c.req.arrayBuffer()
const result = await faceService.recognize(image) // 3-10 seconds
await markAttendance(result.studentId)
return c.json({ ok: true })
})This works — with one camera. With twenty-five cameras running at once, your application is simply occupied waiting for responses.
The correct shape has three stages:
- Accept the image, store it, create a task.
- Respond immediately.
- The AI service sends you a callback when the result is ready.
app.post('/attendance/scan', async (c) => {
const key = await storage.put(await c.req.arrayBuffer())
const task = await db.insert(faceTasks)
.values({ imageKey: key, cameraId, status: 'pending' })
.returning()
await faceService.submit({ imageKey: key, taskId: task.id })
return c.json({ taskId: task.id }) // immediately
})Now waiting for a response does not block your application.
The callback URL — a trap I ate
The most painful bug in this integration turned out to be extremely simple: the callback URL was wrong.
The AI service was doing its job — hundreds of tasks processed, results ready. But they were reaching nobody, because the address I had registered did not match the actual route in the backend.
The worst part is that it failed silently. The AI service sent a POST, received a 404, and wrote it into its own log. On my side no error was visible — tasks simply stayed in the pending state.
Two lessons came out of that.
First: after registering a callback URL, test it. Send one test request by hand and confirm it actually arrives. That is two minutes of work.
Second, and more important: monitor the number of pending tasks. If the count of tasks in pending older than five minutes is not zero, an alert should fire. That one check would have shown me the bug in minutes rather than days.
The general rule: you need observability on both sides of an integration. If the external service cannot tell you, you have to count "what I am waiting for" yourself.
Receiving callbacks reliably
A callback is a webhook, and it brings every webhook problem with it: duplicate delivery, out-of-order arrival, forged requests.
Minimal protection:
app.post('/face-ai/callback', async (c) => {
if (!verifySignature(c)) return c.text('unauthorized', 401)
const { taskId, studentId, confidence } = await c.req.json()
const updated = await db.update(faceTasks)
.set({ status: 'done', studentId, confidence, completedAt: new Date() })
.where(and(
eq(faceTasks.id, taskId),
eq(faceTasks.status, 'pending'), // only once
))
.returning()
if (updated.length === 0) return c.text('ok') // duplicate — silently
await enqueue('attendance:apply', { taskId })
return c.text('ok')
})The status = 'pending' condition provides idempotency: if the same callback arrives twice, the second one does nothing.
Notice that attendance is not recorded inside the callback; the work is only enqueued. The reason is the same as before — a callback has to answer fast.
Working with probability
This is the interesting part. The AI service does not tell you "this student is Anvar". It tells you "the probability this is Anvar is 0.87".
So: is 0.87 enough?
The answer depends on the cost of a mistake, and that is a product decision, not purely an engineering one.
There are two kinds of error and they are not equal:
- Marking the wrong person. Anvar did not come, but the system recorded him as present. This is worse — incorrect information reaches a parent.
- Failing to mark someone who came. Anvar was there but the system did not recognise him. Also bad, but easily corrected: a teacher marks it manually.
The second error is cheaper, so setting the threshold high is right. When unsure, the system should not decide.
In practice I found a three-zone approach useful:
- High confidence — accepted automatically
- The middle zone — goes into a list for human confirmation
- Low confidence — discarded
The middle zone matters most. Without it you have only two options: be wrong, or lose data. The middle zone gives the honest answer "I do not know" and leaves the decision to a person.
Data quality is the real constraint
One important truth: an AI service's accuracy is usually determined not by the model but by the input data.
In the pilot school, 306 of 336 students had photographs registered in the system. The remaining 30 had none — and for them the system could never work at all.
That is not a technical problem, but it looks like one: a teacher says "the system is not working", when in fact that student simply has no data.
So an integration like this needs a coverage metric: how many entities are registered and how many are not. For the product, that number matters more than an accuracy figure, because it points at a fixable problem.
The list of failure states
States you have to plan for in an integration like this:
- The AI service does not respond — the task stays
pending, retried after a timeout - The callback never arrives — the pending-task alert
- A callback arrives with an unknown task id — log it and discard
- The same callback arrives twice — caught by the idempotency condition
- Confidence below the threshold — into the human review list
- The service responds in an unexpected format — validation and a
failedstate
On that last point: always validate an external service's response. AI services sometimes return unexpected shapes, and that crashes your code somewhere confusing.
The general pattern
This article was about face recognition, but the pattern is the same for any slow, uncertain service: document recognition, text analysis, image generation, translation.
The general form:
- Accept the request, create a task, respond immediately.
- Submit the task to the external service.
- Receive the result via callback, accept it idempotently.
- Enqueue the processing.
- Split by confidence into three zones.
- Monitor the number of pending tasks.
The sixth point is the most commonly skipped and the most painful to skip. AI integrations do not crash — they quietly stop. And if you are not counting what you are waiting for, you will hear about it from a user first.