Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A team proposes moving order pricing rules from Java into PostgreSQL functions to cut round trips. Give a balanced review: what belongs in the database, what belongs in the service, and how you would decide here.

The database is the right place for rules that must hold for every writer, such as NOT NULL, CHECK, UNIQUE, foreign key and exclusion constraints, and for set-based work close to the data. The service is the right place for business logic that changes often and needs tests, versioning, libraries and horizontal scaling, which describes pricing rules. So I would keep pricing in Java, put integrity rules such as non-negative quantities in constraints, and cut round trips with batching, fetch joins or single set-based statements; if some logic does move into the database, it gets the same version control, migrations, tests and review as any code.

Why this question is asked

Moving logic into stored functions is a recurring proposal, usually triggered by a slow endpoint that makes thirty small queries. It is a real trade-off, not a matter of taste, and a senior engineer is expected to review it on its merits rather than repeat a slogan. Interviewers ask it to see whether we know what each layer is good at and whether we can find the actual cause of the performance problem. In this answer, we will recap what the database does better and what the service does better, look at why pricing in particular sits on the service side, fix the round-trip problem without moving the rules, and set the conditions under which database code is acceptable.

1What the Database Is Good At

The database sees every write, whoever sends it: the order service, a batch import, a support tool or someone running SQL by hand. That makes it the only place where a rule is truly guaranteed. Declarative constraints, rules we state rather than code, express such rules cheaply: NOT NULL, CHECK (quantity > 0), UNIQUE (order_id, line_no), foreign keys, and in PostgreSQL exclusion constraints that forbid overlapping ranges, for example two bookings of the same room at the same time.

The database is also very good at set-based operations, statements that work on many rows at once close to where they are stored. Updating the status of 200,000 orders with one UPDATE is far cheaper than loading them into Java and saving them back one by one, because no rows travel over the network.

SQL
ALTER TABLE order_line ADD CONSTRAINT qty_positive CHECK (quantity > 0);
ALTER TABLE order_line ADD CONSTRAINT price_not_negative CHECK (unit_price >= 0);
INSERT INTO order_line (order_id, quantity, unit_price) VALUES (7, -2, 10);
-- ERROR: new row for relation "order_line" violates check constraint "qty_positive", the row is refused

Notice that this rule protects us even from a bug in a future service or a hand-written fix-up script. That is the kind of rule that belongs in the database.

2What the Service Is Good At

Application code has strengths that matter for rules that change. It is easy to unit test a pricing class with hundreds of cases in milliseconds. It is versioned and deployed together with the code that calls it, so a new discount ships with a feature flag and can be rolled back with the service. It has rich libraries for money, dates, rule engines and calls to other systems. A debugger, logs and traces show exactly why a price came out as it did. And CPU work scales horizontally: we can run twenty service instances, while the primary database is a single machine that every team shares.

Pricing rules are a typical case of business logic that changes often: promotions, customer tiers, regional taxes, coupons that expire next Friday. They are also logic, with many branches and exceptions, rather than a property of the data. That combination points firmly to the service.

Where each kind of rule belongs
RulePlaceReason
quantity > 0, price >= 0CHECK constraintmust hold for every writer
one line number per orderUNIQUE constraintintegrity, enforced cheaply
no overlapping bookingsexclusion constraintrace-free only in the database
tiered and promotional pricingservicechanges weekly, needs tests and flags
recalculate 200k order totalsone set-based UPDATEdata stays where it lives
tax from an external providerservicenetwork calls, retries, timeouts
Integrity rules go in constraints; changing business logic goes in the service.

3Finding the Real Cause of the Round Trips

The proposal exists because the current code is slow, so we should look at why. Usually pricing an order loads the order, then each line, then each product, then each price list, one query at a time. That is the N+1 query problem: one query for the parent and one more for each child. With 30 lines and 1 millisecond per round trip, that is 90 milliseconds before any rule runs.

We can remove most of that cost without moving a single rule. We fetch everything pricing needs in one or two queries, using a fetch join or an entity graph, or a single query that returns lines with their product and price data. Hibernate batch fetching (@BatchSize or hibernate.default_batch_fetch_size) turns many small lookups into a few IN queries. Then the rules run in memory, which takes microseconds.

Java
// Before: 1 + 30 + 30 queries for a 30-line order
Order order = orders.findById(id).orElseThrow();
for (OrderLine l : order.getLines()) price(l.getProduct().getPriceList()); // lazy loads each time
// After: one query loads what pricing needs, the rules stay in Java
@Query("select o from Order o join fetch o.lines l join fetch l.product p join fetch p.priceList where o.id = :id")
Optional<Order> findForPricing(@Param("id") long id);
Order order = orders.findForPricing(id).orElseThrow(); // 1 query
BigDecimal total = pricingEngine.price(order, customerTier, today); // in memory, unit tested

When a computation really is set-based, such as repricing every open order after a price list change, a single SQL statement is natural and we can write it in SQL, or run the Java engine in a batch job over chunks. The choice is per operation, not a principle for the whole codebase.

4If Logic Does Move Into the Database

Sometimes a function in the database is the right answer, for example a calculation that must be identical for a reporting tool and the service, or a heavy aggregation. Then we treat it as code, not as configuration someone changes in production. Its source lives in the repository, changes go through Flyway or Liquibase migrations, it has automated tests, either with pgTAP inside PostgreSQL or with Testcontainers from the Java test suite, and it goes through the same code review.

We also plan for the costs we take on. Deployment becomes coupled: a function change and a service change must be released in the right order and stay compatible during a rolling deployment, so we version functions (price_order_v2) rather than change them in place. CPU spent in PL/pgSQL is spent on the shared primary, which is harder to scale than service instances. And the logic is tied to PostgreSQL, which matters if we ever change databases.

5How I Would Decide Here

For this proposal, my review would say: measure first. If the endpoint is slow because of N+1 queries, fix the data access and keep the pricing rules in Java, where the team can test and release them weekly. Add constraints for the integrity rules that pricing relies on, such as non-negative prices and quantities, so bad data cannot get in from any path. If after that a specific calculation is still data-heavy, move only that calculation into one well-tested SQL statement or function, with migrations and tests. I would write this down as a short decision record, so the next team knows why pricing is in the service.

Step throughDeciding where a rule lives
  1. Must it hold for every writer?integrity of stored data
    YesConstraint in the databaseNoNext question
  2. Is it set-based over many rows?bulk update, aggregation
    YesSingle SQL statementNoNext question
  3. Does it change often or call other systems?promotions, tiers, taxes
    YesService code with testsNoEither; prefer the service

3 steps in order. Play them, or step through them one at a time.

6Follow-up questions

Are triggers a good way to enforce pricing rules?

No. Triggers run hidden logic on every write, which makes behaviour hard to see and debug and slows bulk operations. They are acceptable for narrow technical jobs such as setting updated_at or writing an audit row, but business rules like pricing should be visible in service code.

How do you test a PostgreSQL function from Java?

With Testcontainers we start a real PostgreSQL in a container, run the Flyway migrations that create the function, and call it through JDBC in ordinary JUnit tests, asserting the results for many inputs. pgTAP is an alternative that writes the tests in SQL and runs them inside the database.

Does keeping logic in the service mean no SQL skills are needed?

Not at all. The fix for the round trips is good SQL and good use of fetch joins and batching. Knowing what the database can do lets us keep rules in the service and still access data efficiently.

7Conclusion

In this answer, we saw that the database is the only place that enforces rules for every writer, so integrity belongs in constraints, and that it is excellent at set-based work. The service is better for business logic that changes often, because it is easy to test, version, debug and scale, and pricing fits that description. The round trips that motivated the proposal are usually N+1 queries that fetch joins, batch fetching or a single statement can fix, and any logic that does move into the database must be versioned, migrated, tested and reviewed like other code.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start by agreeing on what each layer is good at. The database sees every writer, so integrity rules belong there as constraints: NOT NULL, CHECK quantity greater than zero, unique keys, foreign keys, and exclusion constraints for things like overlapping bookings.

Then, if they want more

It is also great at set-based work, like repricing all open orders in one statement. The service is better at business logic that changes often: it is easy to unit test, it is versioned and deployed with the feature, it has libraries, debugging and tracing, and its CPU scales horizontally while the primary database is shared.

Pricing rules change weekly and have many branches, so they belong in the service, but the integrity they rely on, like non-negative prices and quantities, should be constraints. Then I would look at why there are so many round trips.

Usually it is N+1 loading of lines, products and price lists, which a fetch join, an entity graph or batch fetching fixes, bringing thirty queries down to one or two while the rules stay in Java.

If a specific calculation is genuinely data-heavy, I would move only that part into a single SQL statement or function, and it would live in the repository, ship through Flyway migrations, be tested with Testcontainers or pgTAP and be reviewed like any other code. I would record the decision so the next team knows why.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A team proposes moving order pricing rules from Java into PostgreSQL functions to cut...": https://scrivio-interview-library.netlify.app/databases/stored-code/a97132bac7/