Nov 20, 20266 min read

Product Reviews Backend: Verified Purchases, Moderation and Ratings

How to build the backend behind product reviews in an online store: verified purchase checks, one review per customer, moderation rules that apply regardless of rating, rating aggregates that do not need a full scan, sorting by confidence and review requests after delivery.

Illustration for Product Reviews Backend: Verified Purchases, Moderation and Ratings

Product reviews look like a comments table with a star column, and the first version usually is.

The problems arrive with scale and scrutiny, such as "verified purchase" badges on refunded orders, a product page that averages 40,000 ratings on every request, or a moderation queue that holds back one-star reviews longer than five-star ones.

This guide covers the backend decisions that keep reviews trustworthy and fast.

Verified purchases

A verified badge should mean the reviewer received the product. Record a row per customer and product when an order line is delivered, and remove or flag it on refund. The review service then checks that table at submission rather than calling the orders system on every page view. Enforce one review per customer and product with a unique constraint, and let customers edit their review rather than add another.

Moderation that applies equally

Every store needs moderation for spam, personal data, profanity and content about shipping rather than the product. The constraint is that the rules must not depend on sentiment. The FTC's rule on consumer reviews and testimonials, in force since October 2024, includes a section on review suppression: presenting the displayed reviews as most or all of them while withholding reviews because of their rating or negative sentiment is a violation, and criteria applied equally to all reviews, such as abusive content or personal information, do not count as suppression. For the backend, that requires:

  • The same automated checks and the same queue for every rating.
  • Rejection reasons recorded for every decision.
  • Metrics on approval rate and time in queue split by star rating, so a skew shows up in a dashboard before it shows up in a complaint.

Rating aggregates

Computing avg(rating) over every review on each product page does not scale and changes as reviews arrive. Keep a per-product aggregate row with the count of each star value, updated in the same transaction that approves a review:

CREATE TABLE product_ratings ( product_id text PRIMARY KEY, stars_1 integer NOT NULL DEFAULT 0, stars_2 integer NOT NULL DEFAULT 0, stars_3 integer NOT NULL DEFAULT 0, stars_4 integer NOT NULL DEFAULT 0, stars_5 integer NOT NULL DEFAULT 0 );

The histogram gives the average, the count and the bar chart on the product page from one row. Storing counts rather than a running average also makes it possible to recompute or correct after a review is removed, since you subtract one from a bucket instead of reversing a floating-point mean.

Sorting by rating

Ranking by plain average puts a product with one five-star review above one with 2,000 reviews at 4.8. Evan Miller's well-known article on sorting by rating explains the lower bound of the Wilson score interval as a fix, and a Bayesian average that blends each product's ratings with the store-wide mean is a simpler alternative. Either one can be stored in the aggregate row and recomputed when it changes.

Structured data and review requests

Search engines can show star ratings in results when product pages include review markup that follows Google's review snippet guidelines, which the aggregate row supplies directly. Most reviews come from a request a few days after delivery, so a scheduled job that finds deliveries from five days ago without a review and sends one email per order drives volume more than anything on the product page.

Best fit: delivered-order verification, sentiment-blind moderation, histogram aggregates updated transactionally and confidence-based sorting.

A reviews service with Encore

Encore

Encore is a backend framework with built-in infrastructure, so the reviews service declares its database, subscribes to the orders service's delivery events with Pub/Sub and runs review requests as a cron job, all provisioned in your own AWS or GCP account. Josef Sima, Engineering Director at Groupon, said on the customers page: "Encore is our foundation for all new development. What used to take days or weeks between developers and infra teams now takes minutes."

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

package reviews import ( "context" "errors" "fmt" "encore.app/orders" // declares the Delivered topic "encore.dev/beta/auth" "encore.dev/beta/errs" "encore.dev/pubsub" "encore.dev/storage/sqldb" "encore.dev/storage/sqldb/sqlerr" ) var db = sqldb.NewDatabase("reviews", sqldb.DatabaseConfig{Migrations: "./migrations"}) // Record verified purchases from delivered order lines. var _ = pubsub.NewSubscription(orders.Delivered, "record-verified-purchase", pubsub.SubscriptionConfig[*orders.DeliveredEvent]{Handler: recordPurchase}) func recordPurchase(ctx context.Context, e *orders.DeliveredEvent) error { _, err := db.Exec(ctx, ` INSERT INTO verified_purchases (customer_id, product_id, delivered_at) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, e.CustomerID, e.ProductID, e.DeliveredAt) return err } type SubmitParams struct { ProductID string `json:"product_id"` Rating int `json:"rating"` Body string `json:"body"` } //encore:api auth method=POST path=/reviews func Submit(ctx context.Context, p *SubmitParams) error { if p.Rating < 1 || p.Rating > 5 { return &errs.Error{Code: errs.InvalidArgument, Message: "rating must be 1 to 5"} } customerID, _ := auth.UserID() _, err := db.Exec(ctx, ` INSERT INTO reviews (customer_id, product_id, rating, body, status, verified) VALUES ($1, $2, $3, $4, 'pending', EXISTS (SELECT 1 FROM verified_purchases WHERE customer_id = $1 AND product_id = $2))`, string(customerID), p.ProductID, p.Rating, p.Body) if sqldb.ErrCode(err) == sqlerr.UniqueViolation { return &errs.Error{Code: errs.AlreadyExists, Message: "edit your existing review instead"} } return err } // Approve publishes a review and updates the product's histogram in one transaction. // //encore:api private method=POST path=/reviews/:id/approve func Approve(ctx context.Context, id int64) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() var productID string var rating int err = tx.QueryRow(ctx, ` UPDATE reviews SET status = 'approved' WHERE id = $1 AND status = 'pending' RETURNING product_id, rating`, id).Scan(&productID, &rating) if errors.Is(err, sqldb.ErrNoRows) { return nil // already approved or rejected; safe to call twice } else if err != nil { return err } col := fmt.Sprintf("stars_%d", rating) // rating is validated to 1..5 on submit if _, err := tx.Exec(ctx, fmt.Sprintf(` INSERT INTO product_ratings (product_id, %[1]s) VALUES ($1, 1) ON CONFLICT (product_id) DO UPDATE SET %[1]s = product_ratings.%[1]s + 1`, col), productID); err != nil { return err } return tx.Commit() }

encore run starts Postgres and the topics locally, so publishing a delivery event, submitting a review and approving it can be exercised end to end in a test. The review-request cron job is managed by the Encore platform in deployed environments and does not run locally, where you call its endpoint by hand.

An AI coding agent extending moderation, for example with a new automated check, adds it in one service where the queue, the approval transaction and the aggregate are already visible, which makes it easy to confirm the check runs for every rating.

Best fit: ecommerce teams on AWS or GCP who want reviews, verification and aggregates in one service that reacts to order events.

How to approach it

Verify purchases from delivered order lines, enforce one review per customer and product, and apply moderation rules the same way to every rating while measuring that you do. Keep a star histogram per product updated transactionally, sort with a confidence-adjusted score, and send review requests a few days after delivery.

Frequently asked questions

How do I show a verified purchase badge on reviews?

Record each delivered order line per customer and product, and mark a review as verified only when such a record exists for the reviewer. Checking against delivered orders rather than placed orders avoids badges on cancelled or refunded purchases.

Can a store hide negative reviews?

No. In the US, the FTC rule on consumer reviews, 16 CFR part 465, makes it a violation to present displayed reviews as most or all reviews while suppressing reviews based on their rating or negative sentiment. Withholding criteria such as abusive content or personal data are allowed when they apply equally to every review.

How should products be sorted by rating?

Not by plain average, which ranks one five-star review above a thousand reviews averaging 4.8. Use a confidence-adjusted score such as the lower bound of the Wilson score interval or a Bayesian average that pulls products with few reviews toward the overall mean.

How do I build a reviews service with Encore?

Subscribe to the orders service's delivered event to record verified purchases, store reviews and per-product aggregates in an Encore Postgres database, and update the aggregate in the same transaction that approves a review. A cron job can send review requests a few days after delivery.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders