AI-Assisted Implementation: Data, APIs, and Background Jobs
Implement migrations, API contracts, tenant isolation, and reliable background processing, and learn the typical mistakes assistants make in each.
Introduction
Business logic is the part of a system that people notice. Data, APIs, and background processing are the parts that fail in production. They are also where AI-generated code is most likely to look right and be subtly wrong: a missing index, a forgotten tenant filter, a job that runs twice and charges twice.
This lesson covers implementation patterns for these three areas and the review habits that catch assistant mistakes.
Learning Objectives
- Write and review database migrations that are safe and reversible.
- Implement an API from a contract, with consistent error handling, pagination, and authorization.
- Enforce tenant isolation in every data access path.
- Implement idempotent, retry-safe background jobs.
- Test data-layer and job behavior against a real database.
- Recognize common assistant errors in these areas.
1. Migrations
Schema changes are code that runs once, against real data, often irreversibly. Treat them with more care than application code.
Guidelines:
- One migration per logical change; never edit a merged migration, add a new one.
- Prefer additive, backward-compatible changes: add a nullable column, backfill, then add constraints. This allows deployments where old and new code run together.
- Declare constraints in the database: primary and foreign keys,
NOT NULL,UNIQUE,CHECK. - Add indexes for the queries you actually run, especially on foreign keys and tenant columns.
- Provide a rollback path or a documented reason why there is none.
- Test migrations on a copy of realistic data, and against an empty database.
1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE feedback_item (
id BIGSERIAL PRIMARY KEY,
workspace_id BIGINT NOT NULL REFERENCES workspace(id),
body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 10000),
source TEXT NOT NULL,
received_on DATE NOT NULL,
fingerprint TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT uq_feedback_fingerprint UNIQUE (workspace_id, fingerprint)
);
CREATE INDEX ix_feedback_workspace_received
ON feedback_item (workspace_id, received_on DESC);
Common assistant errors: missing indexes, missing NOT NULL or constraints, destructive changes presented casually (DROP COLUMN), column renames that break running code, and migrations that lock a large table.
Ask the assistant to review a migration against these points, but run it yourself.
2. Contract-First APIs
Define the API contract before implementing, using the architecture’s API design, and keep it as an executable artifact (an OpenAPI document or equivalent). Then:
- Generate or write the implementation against the contract.
- Validate requests and responses against it in tests.
- Treat contract changes as deliberate, reviewed changes.
Consistent conventions matter more than any particular choice:
| Concern | Convention (illustrative) |
|---|---|
| Errors | One error shape: code, message, details, request_id |
| Status codes | 400 invalid input, 401 unauthenticated, 403 forbidden, 404 not found, 409 conflict, 422 semantic validation failure |
| Pagination | Cursor-based for lists that grow: ?limit=50&cursor=... |
| Idempotency | Safe retries for create operations that matter (idempotency key or natural key) |
| Versioning | Documented strategy; additive changes within a version |
Assistants often invent a new error format for each endpoint. Put the convention in the instruction file and show an existing endpoint as the pattern to follow.
3. Tenant Isolation
SignalDesk is multi-tenant: every customer workspace must see only its own data. A single missing filter is a data breach. Make isolation structural, not something each developer (or assistant) must remember.
Approaches, from simple to strong:
- Repository convention: all data access goes through repository classes that require
workspace_idas a mandatory parameter. - Row-level security in the database, where supported, as a second line of defense.
- Tests that create data in two workspaces and assert that nothing leaks across any endpoint.
1
2
3
4
5
6
7
8
9
10
11
12
13
class FeedbackRepository:
def __init__(self, session, workspace_id: int):
self._session = session
self._workspace_id = workspace_id # required, never optional
def list_recent(self, limit: int = 50):
return (
self._session.query(FeedbackItem)
.filter(FeedbackItem.workspace_id == self._workspace_id)
.order_by(FeedbackItem.received_on.desc())
.limit(limit)
.all()
)
Also check authorization at the object level: knowing an item’s ID must not allow access to it unless the user’s workspace owns it. This class of flaw (accessing someone else’s object by changing an identifier) is among the most common and serious in web applications, and assistants frequently omit the check because the happy path works without it.
4. Background Jobs
Large imports, summaries, and notifications run in the worker. Jobs fail, restart, and run twice. Design for that:
- Idempotent: running a job twice produces the same result as once. Use unique keys, upserts, or “already processed” markers.
- Retry with backoff, and a maximum, followed by a dead-letter state that a person can inspect.
- Small units of work: process in batches with progress saved, so a failure does not restart a huge job from zero.
- Visible state:
queued,running,succeeded,failed, with timestamps and error summaries a user or operator can see. - Transactional consistency: if a database change and a job enqueue must succeed together, use a pattern such as a transactional outbox rather than hoping both happen.
- Timeouts and cancellation for work that can hang.
1
2
3
4
5
6
7
8
9
10
11
Implement the background import job for FR-IMP-01.
Requirements:
- The API stores the uploaded file reference and creates an import_job
row with status "queued", then returns 202 with the job id.
- The worker processes rows in batches of 500, saves progress after
each batch, and is safe to run again on the same job.
- Failed batches retry up to 3 times with backoff; then the job is
marked "failed" with a summary.
Constraints: follow the repository pattern; no raw SQL in services;
workspace_id required everywhere. First propose the design and the
failure scenarios you will handle; wait for my approval.
5. Test With the Real Thing
Mocks of the database or queue hide the most important failures: constraint violations, transaction behavior, locking, and query plans.
- Run integration tests against a real database (a disposable instance started by your Compose file or test fixtures).
- Test concurrency where it matters: two simultaneous uploads of the same file.
- Test failure paths: the job crashes mid-batch and is rerun.
- Test isolation: two workspaces, assertions in both directions.
The next course covers testing in depth. Here, write enough tests to trust the data, API, and job behavior you just built.
6. Typical Assistant Mistakes in This Area
| Mistake | Why it matters |
|---|---|
| Query inside a loop (N+1) | Slow at scale; invisible with tiny test data |
| Missing tenant or authorization check | Data exposure |
Broad except Exception: pass |
Failures disappear |
| Invented library functions or outdated APIs | Code does not run, or behaves unexpectedly |
| Logging request bodies or personal data | Privacy leak |
| Non-idempotent job | Duplicates and inconsistent state on retry |
| Unbounded queries and results | Memory exhaustion, timeouts |
| Silent schema changes | Breaks other code or deployments |
Keep this table next to your review checklist. It tells you where to look hardest.
7. Practical Exercise
For SignalDesk (or your project):
- Write migrations for the slice 1 tables with constraints and indexes, and test them against an empty and a populated database.
- Write or update the API contract for upload, job status, and list endpoints, including the error format and pagination.
- Implement the endpoints against the contract; validate responses in tests.
- Implement tenant isolation through repositories, and add a two-workspace test that attempts cross-tenant access through every endpoint.
- Implement the background import job with idempotency, batch progress, and retries. Prove idempotency by running the same job twice and by killing it mid-batch.
- Use the AI review prompt below on your implementation, and verify each finding yourself.
1
2
3
4
5
6
7
8
Review the following migration, API handler, repository, and job for:
tenant-isolation gaps, authorization flaws, missing constraints or
indexes, non-idempotent behavior, unbounded operations, swallowed
errors, and personal-data logging. For each finding, give the file
and line, the failure scenario, and a suggested fix. Say clearly if
you are unsure. Do not report style issues.
[paste code]
Verification
You are ready to continue when:
- Migrations apply cleanly on empty and populated databases, with constraints and indexes.
- API behavior matches the contract, and errors use a single format.
- A test proves that one workspace cannot read or modify another’s data through any endpoint.
- The job is idempotent and survives a mid-batch failure.
- Integration tests use a real database.
Key Takeaways
- Migrations, APIs, and jobs fail in production; review them with extra care.
- Make tenant isolation structural, and test it from both directions.
- Design jobs to run twice, fail partially, and be inspected.
- Test against real infrastructure; mocks hide the failures that matter most.
- Know the common assistant mistakes and look for them deliberately.
What’s Next?
As the code base grows, structure degrades unless you actively improve it. Next, we look at refactoring: how to change the design of code safely, with and without AI.