Adding a customer name to an order screen sounds like a small change. You ask your IDE to do it, run the tests, and open a pull request. The page loads quickly on your machine. When someone opens a full page of orders, the application runs 51 queries for 50 rows. In the same application, the order detail route fetches records by ID for any signed-in user, including someone from a different company.
Both problems can fit in a small diff. The demo shows the right customer name and the route returns the expected JSON. Two questions would have changed that review. How many times does the application hit the database for one page? Who is allowed to see a particular order? When you use AI in your IDE, turn those questions into requirements and check the answers in the code, the tests, and the measurements.
A short request leaves too many decisions open
“Optimize the order list” gives the IDE room to change quite a lot. It might suggest caching the entire response in Redis for five minutes. If the cache key contains only the page number, two companies can receive the same data. It might also switch from numbered pages to a cursor. The query could get faster while breaking the client that reads total or jumps directly to page 20.
Start with the current behavior. Point the IDE to the route, the authorization policy, the resource that builds the JSON response, and the tests that describe the contract. Say which fields, filters, and access rules the change needs to support. “Make it faster” becomes more precise when you can point to time spent in the database, in serialization, or waiting for another service. If you still need to find the bottleneck, ask for a diagnosis backed by evidence before you start editing.
Give the IDE the versions of the runtime, framework, and database as well. An API in the latest documentation may be missing from the version in composer.lock or the JavaScript lockfile. When a task spans several layers, ask the agent which files it expects to change and which decisions need your input. You can settle something as simple as how to break a tie between orders with the same timestamp before the change spreads through the application. [1]
Test data hides the cost of a full page
In a multi-tenant order portal, each company has its own logical space, called a tenant. Assume the list route has already checked the user's permission and that $tenantId comes from a tenant context validated on the server. In Laravel, “add the customer name” could produce something like this.
$orders = Order::where('tenant_id', $tenantId)
->orderByDesc('created_at')
->orderByDesc('id')
->limit(50)
->get();
$customerNames = [];
foreach ($orders as $order) {
$customerNames[] = $order->customer?->name;
}
If the customer relationship is lazy-loaded, accessing it inside the loop can trigger a query for every order. With 50 orders linked to customers, that can mean one query for the list and another 50 for the relationship. With two test orders, the response looks right and the extra work is easy to miss. It starts to matter when many requests do the same work at the same time. [2]
For a screen that already supports cursor pagination, fetch the required fields and load the customers in one batch. In this example, the database ensures that each order can only reference a customer from the same tenant.
$orders = Order::query()
->select(['id', 'customer_id', 'created_at', 'total_cents'])
->where('tenant_id', $tenantId)
->with('customer:id,name')
->orderByDesc('created_at')
->orderByDesc('id')
->cursorPaginate(50);
With this simple relationship, loading a page that includes customers usually takes two queries. The full request can still run other queries for authentication, authorization, or response building. The select includes customer_id so the ORM can match each order to its customer. The id breaks ties between orders with the same timestamp. Laravel's cursor paginator needs the sort columns in the result, and those columns must be non-null. If the screen only needs an item count per order, consider withCount() to avoid loading and serializing every item. [2] [3]
In PostgreSQL, (tenant_id, created_at DESC, id DESC) is a candidate index for that query. Check the plan in a test environment with a representative distribution of data. For a read query, EXPLAIN (ANALYZE, BUFFERS) shows what the database executed, including row counts, timings, and buffer activity. The ANALYZE option executes the statement, which matters if someone suggests using it on a write. Measure the index's cost in write performance and storage, too. [4] [5]
Record a baseline before the patch. Run the same workload after the change with small and large tenants and compare queries per page, p95 latency, throughput, and error rate. A sample target might be a p95 below 250 ms with 30 concurrent requests. In that test, 95% of measured latencies would have to fall below the target. Use the service's actual budget when deciding whether the change is ready, and watch connection pool wait time. A query can get faster in isolation and still compete for resources with the rest of the application.
When an export tries to do everything at once
“Add a button that exports all orders” can turn into an unbounded get(), a map(), and a CSV assembled entirely in memory. A hundred rows work fine. With hundreds of thousands, the process holds memory as it hydrates models, transforms rows, and builds the file. A timeout can also prompt someone to click again and start a second expensive export.
Decide how much work belongs in one request. For a large export, use a job that reads batches in a stable order and writes the file incrementally. If the report needs to represent a specific point in time, define how it handles changes made during the run and choose a suitable snapshot or materialization strategy. Limit concurrent jobs and check authorization when the user requests the export and when they download it. If the system reuses an earlier export, make sure its contents still fit the user's current permissions. [6]
The same kind of problem shows up in Node.js when “speed up the calls to the supplier” becomes Promise.all(ids.map(id => fetchOrder(id))). With a large list, the code can start every call before any of them finishes. Bound concurrency to what the service and its connection pool can handle. Set a timeout per call, a deadline for the batch, and a cap on retries. Test with slow responses and outages. That's when one oversized batch starts delaying work for everyone else.
Who is allowed to see the order
“Create an endpoint that returns an order by ID” can end up as Order::findOrFail($id) behind login middleware. Without a global scope that filters orders, the lookup checks whether the record exists. The middleware verifies the caller's identity. The application still needs to decide whether that person can see that record. [6]
In a Laravel application that already has an order policy, the detail route can scope the lookup and consult the policy before building the response.
$order = Order::query()
->where('tenant_id', $tenantId)
->findOrFail($id);
Gate::authorize('view', $order);
return new OrderResource($order);
If someone belongs to more than one company, the server needs to validate the active company against their memberships. The policy handles permissions within that company. For instance, someone in finance may see an order that a regular operator can only see if it is assigned to them. The resource should explicitly declare the fields it returns. Sending the whole model can expose an internal field added by a later migration.
Write a test with two companies and users who have the same role. Request an order belonging to the other company and check the status specified by the API contract. In this example, an out-of-scope order returns 404. For an order inside the company, the policy can deny access with 403 if that's how the application handles it. Apply the same access rule to lists, counts, and exports. Filter records by permission before paginating or aggregating so the total also reflects what the caller is allowed to see. [6]
If someone proposes caching the list, authorize each request and work out who can reuse the result. A key based only on the company can still group users with different permissions. The key needs to reflect the access scope, filters, and cursor that shape the response. The design also needs to account for revoked access. Five minutes of staleness might be fine for prices. It can be too long for data that someone who just left the company should lose access to immediately. [6]
Flexible inputs and the data that leaks into logs
“Add flexible search and sorting” might produce a query that interpolates browser-supplied values into whereRaw() or orderByRaw(). In review, follow the input to the point where it becomes SQL. Validate the type, size, and accepted values. Bind query values as parameters, as in where('status', $status). For the sort column and direction, define fixed options such as recent and oldest in code and map them to columns and directions owned by the application. SQL parameters represent values. The query structure needs its own controls. [7]
On the frontend, “show the note with formatting” could turn into v-html with the order note as its input. For plain text in Vue, regular interpolation escapes the content. If the interface needs to accept HTML, define which elements and attributes the product supports and pass untrusted content through an appropriate sanitizer. Apply that rule to content read from the database as well. A note saved yesterday could still have come from a user. [8]
“Add logging so we can see what went wrong” is another loose request. Logging complete request bodies and headers can send cookies, tokens, and personal data to a system with different access and retention rules. Choose the log fields that help with the investigation, such as a correlation ID, the operation, its duration, and the error category. Check what actually gets logged during a realistic failure, including cases where an SDK includes request details in an exception. Use the same data minimization when giving the IDE context. For debugging, use a synthetic payload with the same structure. [9]
The same notification can arrive twice
“Process the payment webhook and mark the order as paid” usually describes a delivery that works on the first try. The generated code might check whether the event exists, update the order, and then mark the event as processed. Two workers can both check before either one writes. Both conclude that the event is new. If the update also grants credit or sends a notification, that effect can happen twice.
Verify the signature against the raw body as directed by the provider. For a local effect in PostgreSQL, use a unique key that identifies the event. Here the key is (provider, event_id), with both fields required. If the provider guarantees uniqueness only within an account, include the account in the key. After verification, record the event and apply the business change in the same transaction. [10] [11]
INSERT INTO processed_events (provider, event_id)
VALUES ($1, $2)
ON CONFLICT (provider, event_id) DO NOTHING
RETURNING event_id;
Apply the transition only if RETURNING yields a row. If the transaction fails after the INSERT, the event record must roll back too so the next attempt can process it. Some providers can also emit different event IDs for the same business operation. Define the business rule for the transition. You might allow one confirmation per payment ID and prevent a late message from moving a finalized order back to an earlier state. [10] [11]
If processing takes time, durably record the job before acknowledging receipt and handle duplicates in the worker. For an external side effect such as a charge, persist the intent and reuse the same idempotency key when retrying the same operation, if the provider supports it. Check how the provider handles and retains the key. A timeout can leave the result uncertain. Look up the operation's status with the provider before deciding whether to repeat the call. [10] [12]
The agent can run commands too
Asking for a suggestion in the editor and giving an agent a terminal carry different consequences. Depending on the environment's permissions, an agent can install packages, run scripts, and read local files. “Get the build passing” might lead to an unnecessary dependency, a rewritten lockfile, or a removed validation check. Review the suggested command and the files it changes. For every new dependency, check its exact name in the registry, its origin, version compatibility, and the impact of transitive dependencies. Run the project's dependency checks and look for a feature already available in the stack. [1] [13]
Files, ticket comments, and pages opened during the task can contain instructions aimed at the agent. That's a form of prompt injection. Treat that material as task input and enforce limits through the environment. Restrict access to the files, network destinations, and tools the task needs. Use narrowly scoped development credentials and keep production credentials outside that environment. Check which files the IDE can read or send to its service, including files ignored by Git. Review changes to permissions, migrations in shared environments, and deployments before execution. [14]
What a passing test actually proved
A test generated from a patch can copy the assumption that caused the bug. If the endpoint always returns 200 for signed-in users, the test might create one user and one order in the same tenant, assert 200, and stop there. Write expected outcomes from the business rule. Review the test diff alongside the implementation, especially when an assertion disappears or changes to allow a more permissive response.
For database code, use integration tests against the same database engine as production when the behavior depends on transactions, indexes, or constraints. For the webhook, send two concurrent deliveries and check the persisted effect. Force a failure between recording the event and updating the order, then verify that a retry completes the operation. For the order list, compare the number of queries for a small page and a full one. That can catch an N+1 without relying on millisecond timings on a CI runner. Measure latency with a controlled load test.
Open the full diff before merging. A fast query in the branch can arrive with a migration that blocks writes to a busy table. In PostgreSQL, CREATE INDEX CONCURRENTLY allows writes to continue during the build. It has additional costs and constraints, including the need to run outside a transaction block. Check how that fits the project's migration tool. For schema changes, verify that both old and new service versions can operate during deployment. [15]
Run static analysis, dependency checks, and secret scanning in CI. Compare test-environment results with the baseline you recorded before the patch. If the change touches a critical route, agree on what to watch after deployment, such as connection wait time or the route's error rate, and when to roll back. For data changes, plan recovery separately from the code rollback. Reverting the code alone leaves writes that already happened in the database. [1] [13]
A prompt that gives you something to verify
The request “optimize the order list” can include the same contract you'd use to review a teammate's work. In this example, the list already uses a cursor and the ticket is to remove the N+1 for customers.
Investigate the queries used to build one page of the order list in PHP 8.3, Laravel 12, and PostgreSQL 16. Start with the controller, policy, resource, and existing tests. Show where the customer relationship is loaded and explain the smallest change that removes the N+1.
Preserve the JSON fields, filters, and cursor the clients already use. The page contains up to 50 orders, sorted by creation time and ID in descending order. The active company comes from the authenticated tenant context validated on the server. Scope the query to orders the caller can see before paginating. Use the installed dependencies.
Cover a full page, orders with identical timestamps, and a user from another company with the same role. Expect two queries to load orders and customers for any page that contains orders with customers. Count those separately from the other queries in the request. Run the relevant tests and report what you measured. If you suggest an index, show the query it would support.
That request gives the reviewer somewhere concrete to start. Open the test with two companies, check the rule that scopes the query, and look at the query count for a full page. If the PR only shows the screen working with two orders, it still needs the evidence that prompted the change.
References
1. GitHub Docs · Review AI-generated code
2. Laravel 12 · Eloquent relationships and eager loading
3. Laravel 12 · Cursor pagination
4. PostgreSQL · Using EXPLAIN
5. PostgreSQL · Indexes and ORDER BY
6. OWASP · Authorization Cheat Sheet
7. OWASP · SQL Injection Prevention Cheat Sheet
8. Vue · Security best practices
9. OWASP · Logging Cheat Sheet
10. Stripe · Webhook signatures and duplicate events
11. PostgreSQL · INSERT and ON CONFLICT
12. Stripe · Idempotent requests
13. GitHub Docs · Reviewing dependency changes in a pull request
14. OWASP · AI Agent Security Cheat Sheet
15. PostgreSQL · Building indexes concurrently