Imagine you're building a food delivery app.
Your search algorithm already ranks restaurants based on relevance, distance, ratings, and delivery time.
Now your product team wants to introduce sponsored restaurants.
Sounds simple, right? Move the paying restaurant to the top.
But what happens if that restaurant is closed? What if it doesn't deliver to the user's location? What if the user has already seen its advertisement five times today?
Suddenly, sponsored listings become more than an advertising problem.
They become a ranking problem.
In this tutorial, we'll build a working sponsored listings ranker using plain Node.js that combines organic results and paid placements while respecting eligibility, relevance, frequency caps, and event tracking.
No external libraries, databases, or API keys required.
1. Set Up the Restaurant Ranking Problem
We'll work with three restaurants:
- Restaurant A: Open, organic relevance score of 0.94.
- Restaurant B: Open, organic relevance score of 0.86, active advertising campaign.
- Restaurant C: Closed, organic relevance score of 0.99.
Restaurant C also has an active advertising campaign. We'll use it to test whether payment can bypass eligibility.
Without advertising, our expected ranking is:
Position 1: Restaurant A Position 2: Restaurant B Restaurant C must not appear because it is closed.
With sponsored placement enabled, the expected result becomes:
Position 1: Restaurant B [Sponsored] Position 2: Restaurant A Restaurant B receives additional visibility because it is both relevant and eligible.
Restaurant C remains excluded, regardless of its advertising campaign.
Let's implement it.
2. Create the Node.js Project
You'll need Node.js 22 or newer.
mkdir sponsored-ranker cd sponsored-ranker touch ranker.cjs Add the following code to ranker.cjs. Each subsequent code block extends the same file.
const { randomUUID } = require('node:crypto'); const assert = require('node:assert/strict'); const restaurants = [ { id: 'A', open: true, score: 0.94 }, { id: 'B', open: true, score: 0.86 }, { id: 'C', open: false, score: 0.99 } ]; const campaigns = new Map([ ['B', { id: 'camp-B', active: true }], ['C', { id: 'camp-C', active: true }] ]); The relevance scores are predefined to keep the example focused on ranking and sponsored placement rather than machine learning.
In production, these scores could come from your existing search engine, recommendation model, or scoring function.
3. Filter Candidates Before Considering Payment
The first rule of sponsored listings is simple:
Payment cannot override hard eligibility constraints.
Our ranker must exclude closed restaurants before evaluating advertising campaigns.
function getEligibleRestaurants(candidates) { return candidates.filter(r => r.open); } console.log( getEligibleRestaurants(restaurants) .map(r => r.id) ); Output:
[ 'A', 'B' ] Restaurant C has the highest relevance score and an active campaign, but neither matters because it is unavailable.
A production delivery app could extend the filter to enforce:
- Delivery radius.
- Restaurant availability.
- Menu availability.
- Geographic restrictions.
- Account status.
- Marketplace policies.
Eligibility determines what can appear.
Ranking determines where it appears.
Keep those responsibilities separate.
4. Build a Blended Organic and Sponsored Ranker
Our placement policy will enforce four rules:
- Only eligible restaurants can appear.
- Sponsored candidates need a minimum relevance score of 0.75.
- A maximum of one sponsored restaurant can appear at position one.
- A sponsored restaurant cannot also appear as a duplicate organic result.
We'll also introduce a frequency cap of two sponsored impressions per user, per campaign, per UTC calendar day.
First, create our in-memory state:
const impressions = new Map(); const decisions = new Map(); const events = new Map(); const CAP = 2; const day = () => new Date().toISOString().slice(0, 10); const capKey = (userId, campaignId) => JSON.stringify([userId, campaignId, day()]); Now implement the ranking function:
function rank(userId, candidates) { const eligible = getEligibleRestaurants(candidates) .sort((a, b) => b.score - a.score); const winner = eligible.find(r => { const campaign = campaigns.get(r.id); if (!campaign?.active) return false; if (r.score < 0.75) return false; const count = impressions.get( capKey(userId, campaign.id) ) ?? 0; return count < CAP; }); const organic = eligible .filter(r => r.id !== winner?.id) .map(r => ({ id: r.id, sponsored: false })); const results = winner ? [ { id: winner.id, sponsored: true, campaignId: campaigns.get(winner.id).id }, ...organic ] : organic; const decision = { decisionId: randomUUID(), userId, results: results.map((r, i) => ({ ...r, position: i + 1 })) }; decisions.set(decision.decisionId, decision); return decision; } The function performs organic ranking, sponsored candidate selection, frequency-cap validation, placement, and duplicate prevention in one decision.
It also generates a unique decision identifier using Node.js's built-in crypto.randomUUID().
An example response looks like this:
{ "decisionId": "8a2f3e51-7b14-4c92-a6d8-1c9b2e4f5a01", "userId": "u1", "results": [ { "id": "B", "sponsored": true, "campaignId": "camp-B", "position": 1 }, { "id": "A", "sponsored": false, "position": 2 } ] } The frontend now receives one ordered response rather than independently combining search results and advertisements.
It also knows which result must display an advertising label.
The FTC's native advertising guidance emphasizes that paid placements should be clearly identifiable as advertisements.
The sponsored flag gives the frontend the information it needs to display an appropriate label.
5. Track Impressions, Clicks, and Orders
Returning a sponsored restaurant is not the same as displaying it.
A user might close the application before the results render.
If we increment the impression count every time the ranking function runs, our frequency cap and reporting become inaccurate.
Instead, increment the counter when an impression event is recorded.
function track(decisionId, itemId, type) { if (!['impression', 'click', 'order'].includes(type)) { throw new Error('Invalid event type'); } const decision = decisions.get(decisionId); const item = decision?.results.find( r => r.id === itemId && r.sponsored ); if (!item) { throw new Error('Unknown sponsored placement'); } const key = JSON.stringify([ decisionId, itemId, type ]); if (events.has(key)) return false; const event = { decisionId, itemId, type, campaignId: item.campaignId, at: new Date().toISOString() }; events.set(key, event); if (type === 'impression') { const counter = capKey( decision.userId, item.campaignId ); impressions.set( counter, (impressions.get(counter) ?? 0) + 1 ); } return true; } We now have three event types:
- Impression: The sponsored result was rendered.
- Click: The user interacted with the sponsored result.
- Order: An order was associated with the sponsored result.
The event function validates that the restaurant actually appeared as a sponsored result in the recorded decision.
It also prevents repeated submissions of the same event type for the same decision and item.
This is intentionally simplified. Production systems need unique event IDs, transaction IDs, attribution windows, authentication, and durable deduplication.
The architecture gives us a basic traceable chain:
Ranking request | Decision ID | Sponsored placement | Impression | Click | Order An attributed order does not necessarily mean the advertisement caused an incremental order. That requires additional measurement, such as a randomized holdout.
6. Test the Ranker and Frequency Cap
Add these assertions to the bottom of ranker.cjs.
const first = rank('u1', restaurants); assert.deepEqual( first.results.map(r => r.id), ['B', 'A'] ); assert.equal(first.results[0].sponsored, true); assert.equal( track(first.decisionId, 'B', 'impression'), true ); // Duplicate impression should not count again. assert.equal( track(first.decisionId, 'B', 'impression'), false ); track(first.decisionId, 'B', 'click'); track(first.decisionId, 'B', 'order'); const second = rank('u1', restaurants); assert.equal(second.results[0].sponsored, true); track(second.decisionId, 'B', 'impression'); // The campaign has reached its daily frequency cap. const third = rank('u1', restaurants); assert.deepEqual( third.results.map(r => r.id), ['A', 'B'] ); assert.ok( third.results.every(r => !r.sponsored) ); assert.equal(events.size, 4); console.log('First:', first.results); console.log('After cap:', third.results); console.log('Events:', events.size); Run the script:
node ranker.cjs The relevant output is:
First: [ { id: 'B', sponsored: true, campaignId: 'camp-B', position: 1 }, { id: 'A', sponsored: false, position: 2 } ] After cap: [ { id: 'A', sponsored: false, position: 1 }, { id: 'B', sponsored: false, position: 2 } ] Events: 4 Notice what happens after Restaurant B reaches its frequency cap.
It doesn't disappear from search results.
It simply loses its sponsored placement and returns to its natural organic position.
Restaurant C never appears.
That's an important distinction. Advertising eligibility should not determine organic eligibility.
7. Where the DIY Sponsored Listings Ranker Breaks Down
Our implementation works as a single-process demonstration.
But imagine your marketplace grows to thousands of advertisers and millions of daily requests.
Several problems emerge.
Auctions
What happens when five eligible restaurants compete for the same sponsored position?
Our current implementation selects the eligible sponsored restaurant with the highest organic score.
A production auction may also consider bids, predicted engagement, campaign objectives, and placement policies.
Concurrent Frequency Caps
Our in-memory counter works for sequential requests.
But two concurrent requests can both observe an available frequency allowance before either impression arrives.
Production systems need shared state, atomic operations, and potentially reservation mechanisms to manage concurrent delivery.
Campaign Budget Pacing
An advertiser sets a daily budget of $100.
Without pacing, the marketplace could spend the entire budget during the first hour of the day.
Pacing distributes campaign delivery according to budget constraints and available inventory.
Advertiser Self-Service
Restaurant owners eventually need to create campaigns, set budgets, choose products or placements, pause campaigns, and review performance.
That requires a separate advertiser-facing application and supporting APIs.
Finance and Reconciliation
Advertising revenue introduces responsibilities that our ranker does not handle:
- Wallet balances.
- Billable events.
- Campaign spending.
- Invoicing.
- Refunds.
- Financial reconciliation.
Distributed Event Processing
Our Map objects disappear when the application restarts.
Production event processing requires persistent storage, reliable delivery, idempotency, monitoring, and recovery mechanisms.
The simple ranking function has now become a distributed advertising system.
8. When Should You Replace the DIY Ranker With an API?
Once sponsored listings become a production monetization surface, there are two architectural directions.
Option 1: A complete commerce media platform
This makes sense when your marketplace needs extensive advertiser operations, auctions, funding, campaign management, pacing, and reporting.
Option 2: A unified ranking and sponsored-placement decision API
This makes sense when your marketplace already owns candidate retrieval and wants to outsource the decision about how organic and sponsored candidates appear together.
The distinction is important when evaluating a Topsort alternative for sponsored listings infrastructure, where product scope, pricing structure, and ownership of financial operations can materially change integration requirements.
A decision layer such as Gortex can be evaluated for the second architectural approach.
Its published beta focuses on application-supplied candidates, organic ranking, sponsored placement, platform-controlled policies, and decision identifiers.
Your application can retain its existing retrieval infrastructure while delegating configured ranking and placement decisions.
Buyers should verify the supported campaign, auction, billing, and operational capabilities against their production requirements.
Final Thoughts
We built a sponsored listings ranker that:
- Filters unavailable restaurants.
- Preserves organic relevance.
- Inserts an eligible sponsored restaurant.
- Prevents duplicate placements.
- Applies a frequency cap.
- Generates unique decision identifiers.
- Tracks impressions, clicks, and orders.
The code demonstrates an important marketplace architecture principle.
Sponsored listings should not be an unrelated advertising system that blindly inserts paid results into search.
They should participate in a controlled decision process.
Retrieval finds eligible candidates. Ranking determines their order. Sponsored placement creates monetization opportunities within those constraints.
Payment should buy additional visibility, not permission to bypass relevance.
