Skip to main content

Search

Search problems, hooks, and pages

Back to About

Article View Tracking

built with: MongoDB unique + TTL indexes · React Query

A MongoDB unique index doubles as the deduplication check, and a TTL index does the cleanup — no cron job anywhere.

One scroll listener drives two things

A single listener on #article-scroll-pane feeds both the sticky top progress bar and the "you've read this" signal. Reaching about 98% of the pane's scrollable height is the read trigger, so there is no separate IntersectionObserver sentinel to keep in sync with the progress calculation.

Dedup by insert, not by query

recordArticleView tries to insert one document into ArticleViewMark keyed by {articleId, ip, day}, backed by a unique Mongo index on that combination. A repeat visitor produces a duplicate-key error (Mongo code 11000), which is swallowed — only a successful insert increments the permanent ArticleView.count.

That makes the dedup check and the dedup write the same database round trip, instead of a read-then-write that could race between two requests landing at the same moment.

// src/lib/actions/article-views.ts
try {
  await ArticleViewMark.create({ articleId, ip, day });
  await ArticleView.updateOne({ articleId }, { $inc: { count: 1 } }, { upsert: true });
} catch (err) {
  if (isDuplicateKeyError(err)) return; // already counted today
  throw err;
}

A TTL index instead of a cleanup job

ArticleViewMark rows expire on their own: createdAt carries a TTL index set to about 24 hours, so MongoDB removes yesterday's dedup rows itself. There is no cron route or maintenance script — the collection self-cleans.

Counts are read in bulk: GET /api/articles/views returns every count in one response, cached under one React Query key shared by the listing and detail pages, and the read tracker invalidates that key after a successful record.

Important

Gotcha

The insert-then-catch pattern only works because the unique index exists — drop it and every visit would double-count silently, since the try block would simply succeed twice.

Where it lives in the repo

  • src/components/content/article-view.tsx
  • src/components/content/article-read-tracker.tsx
  • src/components/content/article-view-count.tsx
  • src/components/content/use-article-views.ts
  • src/lib/actions/article-views.ts
  • src/models/ArticleView.ts
  • src/models/ArticleViewMark.ts
  • src/app/api/articles/views/route.ts