Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Troubleshoot & Optimize a Slow .NET API

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through diagnosing and fixing a slow .NET API, covering everything from initial investigation to code-level optimizations. You'll learn a repeatable process to identify bottlenecks, apply targeted fixes, and verify improvements—no guesswork required.

What You'll Need

  • Access to the API's source code and build environment.
  • Ability to deploy changes to a test or staging environment.
  • A tool for sending HTTP requests (e.g., Postman, curl, or a browser's dev tools).
  • Optional but helpful: Application Insights or another APM tool, and a SQL Server profiler or equivalent.

Step-by-Step

  1. Reproduce and measure the slowness. Use a tool like Postman or curl to hit the slow endpoint with a realistic request. Record the response time. Run it several times to confirm it's consistently slow, not just a one-off. Note the exact endpoint, parameters, and payload size.
  2. Identify the bottleneck layer. Check if the slowness is in the API itself, the database, or an external service. Look at the response time breakdown in your APM tool if you have one. If not, add temporary logging around the main parts: model binding, action method start, database calls, and before returning the result. This will show where the time is spent.
  3. Check for common configuration issues. Look at your appsettings.json for logging levels (verbose logging can slow things down). Ensure you're running in Release mode, not Debug. Check if the API is behind a reverse proxy that might be buffering or compressing responses unexpectedly.
  4. Review database queries. The most common culprit. Enable query logging (e.g., in EF Core: optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information)) and capture the actual SQL being executed. Run that SQL in a database tool and check its execution plan for table scans, missing indexes, or high row counts. Add indexes on columns used in WHERE, JOIN, and ORDER BY clauses. For complex queries, consider rewriting them or using views.
  5. Look for N+1 query problems. If you're using an ORM like EF Core, check for multiple queries being sent to the database for what should be a single request. This often happens with lazy loading or when you select a list of entities and then access a navigation property for each one. Use Include() to eager load related data, or project to a DTO with Select() to fetch only the needed columns.
  6. Examine synchronous calls and blocking. Ensure you're using async/await for all I/O operations (database calls, HTTP calls, file reads). Avoid .Result or .Wait() on tasks, as they can cause thread pool starvation. Look for any synchronous database calls like .ToList() instead of .ToListAsync().
  7. Optimize serialization. If your API returns large JSON payloads, consider using System.Text.Json (the default) and setting ReferenceHandler to IgnoreCycles to avoid infinite loops. Trim unnecessary fields from the response by using DTOs instead of returning full entities. If the payload is still large, consider enabling compression (e.g., GZip) on the server.
  8. Add caching. For data that doesn't change often, implement in-memory caching using IMemoryCache or a distributed cache like Redis. Cache the results of expensive database queries or external API calls. Set appropriate expiration times. For example, cache a list of product categories for 5 minutes.
  9. Consider response compression. Enable response compression in ASP.NET Core by adding the AddResponseCompression() service and using the UseResponseCompression() middleware. This can drastically reduce the size of JSON responses, especially if they contain repetitive text.
  10. Load test and verify. After making changes, re-run the same requests and compare response times. Use a tool like JMeter, k6, or even a simple script to simulate multiple concurrent users to ensure the fix holds under load. Check that the API's memory usage and CPU are stable.

Common Mistakes

  • Optimizing without measuring. Guessing which part is slow usually leads to wasted effort. Always profile and log first.
  • Ignoring the database. Most slowness comes from SQL. Don't assume the C# code is the problem until you've seen the query plan.
  • Overusing async without understanding it. Making a method async doesn't make it faster; it just frees the thread. If you're doing CPU-bound work, parallelizing it might not help and can even hurt.
  • Returning too much data. Returning entire entities with all their columns and related data is a common cause of slow responses. Use DTOs to limit the payload.
  • Not using indexes. Forgetting to add indexes on foreign keys and frequently queried columns is a classic mistake.

Tips

  • Start with the database. In 80% of cases, the fix is an index or a query rewrite.
  • Use a profiler. Tools like MiniProfiler or Application Insights can show you the exact time spent in each database call and external service.
  • Batch database operations. If you're inserting or updating many rows, use bulk operations instead of a loop of individual calls.
  • Consider using compiled queries in EF Core for frequently executed queries to reduce plan compilation overhead.
  • Keep your dependencies updated. Newer versions of .NET and EF Core often include performance improvements.

Troubleshooting

If the API is still slow after following the steps:

  • Check external dependencies. The slowness might be in a downstream service (e.g., a payment gateway, a cloud storage call). Use a tool like Fiddler or Wireshark to see the time spent on each HTTP call.
  • Look at thread pool starvation. If you see many requests queuing, check the number of threads in the thread pool. You can see this in the diagnostic logs. This often happens when synchronous calls are blocking async methods.
  • Check for memory leaks. A memory leak can cause the GC to work harder, slowing everything down. Use a memory profiler to check for large object allocations that aren't being collected.
  • Review the server's resources. Is the CPU or memory maxed out? If so, the problem might be that you need to scale out (add more instances) rather than optimize code.
  • Try a minimal repro. Create a simple endpoint that does nothing but return a string. If that's slow, the issue is in the middleware pipeline or server configuration, not your business logic.

Frequently Asked Questions

How do I know if it's my code or the database?

Add logging around database calls and measure the time. If the database call takes 90% of the total time, the problem is likely there. Also, check the SQL execution plan for missing indexes or scans.

Is async/await always better?

Not always, but for I/O-bound operations (database, HTTP, file), it's essential. It prevents thread pool starvation and allows the server to handle more concurrent requests. For CPU-bound work, it doesn't help.

Should I use in-memory caching or Redis?

For a single-instance API, in-memory caching is faster and simpler. For multiple instances or if you need to share cache across servers, use a distributed cache like Redis.

How do I enable response compression?

In Program.cs, add builder.Services.AddResponseCompression() and app.UseResponseCompression() before any other middleware that writes to the response. You can also configure which MIME types to compress.

What is the N+1 problem and how do I fix it?

It's when you make one query for a list of items and then one query per item for related data. Fix it by using .Include() to eager load related data or by projecting to a DTO with .Select().

How can I see the actual SQL my EF Core query generates?

Enable logging in your DbContext options: optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information). You'll see the SQL in the console. Alternatively, use a profiler like SQL Server Profiler.