Krzysztof TalarFull-Stack .NET Developer
← All case studies

Diagnosis · 01·Performance·2023·2 min read

CPU from 90% to 25% in my first week on the project

One endpoint took 15 seconds on average and threw OutOfMemoryException. I found the cause and removed it.

90% → 25%API server CPU load after the fix went live
My role
Sole backend developer, new to the project
When
September 2023
Stack
.NET · EF Core · PostgreSQL · Azure App Service · Application Insights · Serilog

Problem

In September 2023 I took over the backend of a loyalty app for a nationwide retail chain, used by about 500,000 people. The API server was running at about 90% CPU, with no headroom left for more traffic.

Diagnosis

In Application Insights I went through the slowest endpoints. One of them took 15 seconds on average, and its logs kept showing OutOfMemoryException. I reproduced the call locally and traced the code in the debugger.

Cause

Every time the app opened, the backend checked whether to assign the user a satisfaction survey. The EF Core query looked harmless, but by loading a related collection it pulled the answers of every user into memory and only then picked one. On top of that, the object was written to the Serilog logs, so the whole collection also had to be serialised. The table grew with every purchase, so the cost crept up until the server hit its performance limit.

Before

  1. App
  2. API
  3. Database: load everyone’s answers
  4. pick one in memory

300,000 rows in memory · ~15 sOutOfMemoryException

After

  1. App
  2. API
  3. Database: load this user’s answer

1 row in memory · milliseconds

Illustrative diagram based on production before the fix: a 15 s average response, and at about 300,000 rows the query ended in OutOfMemoryException.

What I did

I optimised data access in this spot in three steps:

  • Limited the data fetched. The query now loads only the current user’s data instead of the whole table.
  • Added indexes for the new query, so the database no longer scans the whole table.
  • Removed unnecessary writes. The backend writes to the database only when there is actually something to save.

Result

Right after the deploy, CPU load dropped from about 90% to about 25%. The query’s cost no longer depends on the number of users, so it does not creep back as the database grows.

Client names and details that would identify them are withheld under NDA.