# Making a slow admin panel fast: pushing filters and counts into SQL

Nobody benchmarks the admin panel. It is the page only your own team opens, so it grows one quick feature at a time, and every feature is written in the fastest way to ship, not the fastest way to run.

Ours is a FastAPI app with SQLAlchemy on SQLite and Jinja templates. One day the jobs tab took long enough to load that we started opening it in a background tab and coming back later. The dashboard was worse: 5 to 10 seconds under load, and up to 13 on long periods.

Nothing here is exotic. But each fix follows a rule that is easy to forget when the page "only has to work for us", so it is worth writing down.

## Symptom one: the list that loaded everything

The original jobs tab looked roughly like this:

```python
jobs = db.query(Job).all()
jobs = [j for j in jobs if matches(j, q, status)]
jobs.sort(key=sort_key)
ctx["jobs"] = jobs[:200]
```

Every request pulled every job, description included, into Python objects. Then Python filtered, sorted and threw away everything after row 200. Job descriptions are long HTML, so most of that memory was text nobody would see.

The fix is the obvious one: filtering, sorting and the limit belong in SQL. The less obvious part is doing it once, in one helper, so new tabs get it for free:

```python
PER_PAGE = 50

def paginate(request, query, ctx, per_page=PER_PAGE, param="page"):
    total = query.order_by(None).count()
    pages = max(1, -(-total // per_page))
    try:
        page = int(request.query_params.get(param) or 1)
    except ValueError:
        page = 1
    page = min(max(page, 1), pages)
    ctx["pager"] = {"page": page, "pages": pages, "total": total}
    return query.offset((page - 1) * per_page).limit(per_page).all()
```

Three details matter here.

`order_by(None)` strips the ordering before counting. A `COUNT(*)` does not need `ORDER BY`, and on a sorted, filtered query the database may otherwise do real work for nothing.

The page number is clamped. Someone bookmarks page 7, the filter now returns three pages, and the user lands on the last page instead of an empty table.

The `param` argument exists because one tab shows two independent tables. Each gets its own query string key, so paging one does not reset the other.

We also stopped loading what the list never shows. `defer(Job.description)` keeps the heavy column out of list queries entirely.

## Symptom two: 200 queries hiding in a template

With the list fixed, the tab was still slow. The template showed an application counter next to each job:

```jinja
{% for job in jobs %}
  <td>{{ job.applications|length }}</td>
{% endfor %}
```

That innocent attribute is a lazy relationship. Each row fired its own query, and each query loaded full application rows just to count them. With 200 rows on screen that was 200 round trips per page view. The classic N+1, invisible in the Python code because it lived in the template.

The fix is to count for the whole page at once, keyed by id:

```python
ids = [j.id for j in page_rows]
ctx["job_apps"] = dict(
    db.query(Application.job_id, func.count(Application.id))
      .filter(Application.job_id.in_(ids))
      .group_by(Application.job_id)
      .all()
) if ids else {}
```

The template reads `job_apps.get(job.id, 0)`. One query, and its cost no longer depends on how the rows were fetched.

The same pattern then spread through the users tab: jobs per employer, live jobs per employer, applications per candidate, applications received by each employer. Each is a single `GROUP BY` over the ids on the current page. Notice the guard on empty `ids`: an empty `IN ()` is either an error or a full scan depending on the dialect, and it is a wasted query either way.

One counter needed two sources. An "application" for us is either a form submitted on the site or a click through to the employer's own page. Both are a `GROUP BY` on a different table, merged in Python:

```python
apps = dict(count_by(Application.user_id, ids))
for uid, n in count_events("source_click", ids):
    apps[uid] = apps.get(uid, 0) + n
```

Merging two small dictionaries is cheap. Writing it as one SQL query with a `UNION` would be possible, but harder to read and no faster at this size.

## Symptom three: logic that only existed in Python

Some filters could not move to SQL because the rule lived in a model property. For CV moderation we had an `is_empty` property: no real title, a too-short summary, no skills, no history, no file. We wanted empty drafts filtered out of the main queue and handled automatically.

You cannot call a Python property inside a `WHERE` clause. So the rule got a twin that builds the same condition as an expression:

```python
def blank(col):
    return func.trim(func.coalesce(col, ""), " \t\r\n") == ""

def resume_empty_sql():
    return and_(
        func.trim(func.coalesce(Resume.title, "")).in_(("", "Untitled")),
        func.length(func.trim(func.coalesce(Resume.about, ""))) < 40,
        blank(Resume.skills),
        blank(Resume.employment_history),
        blank(Resume.cv_file_path),
    )
```

Now the queue query is `filter(~resume_empty_sql())`, it pages correctly, and the counter in the header matches what is listed.

The cost is that the rule exists twice, and twins drift. Ours did: the Python property later learned that a one-character title like "-" is also empty, while the SQL version still compares against a fixed list. If you take this route, put both versions next to each other and test them on the same fixtures. SQLAlchemy's `hybrid_property` can express both in one place when the logic is simple enough.

## Symptom four: recounting history on every open

The dashboard draws daily charts: page views, clicks to employers, sign-ups, over 7 to 180 days. Each series was a single `GROUP BY date(created_at)`, which looked efficient. But the analytics table had grown to around a million rows, and every open re-aggregated all of them. Around a second per series, several series per page.

The key observation: analytics events are append-only. Once a UTC day is over, its count never changes. So closed days are computed once and kept in process memory, and only today is queried live:

```python
_DAYS = {}  # event name -> (since_day, today, {day: n})

def daily_counts(db, name, since):
    today = utc_midnight()
    hit = _DAYS.get(name)
    if not (hit and hit[0] <= since.date().isoformat()
            and hit[1] == today.date().isoformat()):
        closed = count_by_day(db, name, since, until=today)
        hit = (since.date().isoformat(), today.date().isoformat(), closed)
        _DAYS[name] = hit
    out = {d: n for d, n in hit[2].items() if d >= since.date().isoformat()}
    out.update(count_by_day(db, name, today))
    return out
```

The cache key includes "today", so it invalidates itself at midnight without a timer. A request for a shorter period is served from a cached longer one. The live query touches only today's rows, which takes about 15 ms.

We only enable the cache in production. In tests, fixtures insert events with past dates after the first call, which would make the cache lie. Commit message from that day: charts in 0.25 s instead of 2вАУ13 s, and the new series were checked against the old calculation on a copy of the production data before shipping.

## A planner footnote

The "top viewed jobs" widget uses the same split: closed days from memory, today live. The live part had a surprise. SQLite has two candidate indexes, one on `(name, created_at)` and one on the job id. It picked the job index and scanned every view of every job ever, about 0.46 s.

SQLAlchemy does not emit `INDEXED BY` for SQLite, so we nudged the planner instead. Wrapping the type column in `coalesce(entity_type, '') = 'job'` makes it unusable for the second index, so SQLite takes the date index and reads only today's rows: about 0.05 s. It is a hack, and it carries a comment explaining why it exists. Run `EXPLAIN QUERY PLAN` before trusting any index you add.

## What we took away

- **Count where the data lives.** `query.count()` and `GROUP BY` are almost always cheaper than loading rows to call `len()` on them.
- **Templates are code.** A relationship attribute in a loop is a query per row. Pass precomputed dictionaries instead.
- **One pagination helper.** Clamp the page, strip ordering from the count, allow two pagers per page.
- **Rules used in filters need a SQL form.** Keep it next to the Python form and test both.
- **Immutable history can be cached forever.** Append-only data plus a date boundary gives you a cache that never needs invalidating.

None of this required a new database or a caching server. It was a week of small commits, each one measured against the page someone was actually waiting on. We use this admin panel at [SpinHire](https://spinhire.io), a job board for the iGaming industry.

