Background jobs are common in ASP.NET Core applications. They process queued orders, generate reports, synchronize data, send notifications, import files, and perform scheduled maintenance.

Unlike ordinary HTTP requests, some background jobs can run for several minutes or even hours. During that time, they may perform hundreds of database operations while communicating with external services or processing large amounts of data.

This creates an important database connection management challenge.

A job that opens a database connection and keeps it active throughout its entire execution can unnecessarily occupy connection pool resources. If multiple jobs run concurrently, the application may eventually run out of available connections. Other requests then wait for a connection or fail after reaching the connection timeout.

The problem is not necessarily that the database cannot handle the workload. Sometimes the application simply holds connections longer than necessary.

Entity Framework Core, ADO.NET connection pooling, dependency injection scopes, and asynchronous programming provide the building blocks for handling this correctly.

The goal is to keep database connections available when they are needed, release them when database work is complete, and ensure that long-running operations do not exhaust the connection pool.

Why Long Running Jobs Can Exhaust Database Connections

Consider an ASP.NET Core application that processes customer orders in the background.

The job performs the following operations:

  • Retrieves pending orders.
  • Loads customer information.
  • Calls an external payment service.
  • Updates order status.
  • Sends a notification.
  • Records processing results.

Suppose the job takes 10 minutes to complete.

If the application opens a database connection at the beginning and keeps it open until the entire job finishes, that connection remains unavailable to other operations even when the job is waiting for an external API response.

The problem becomes more serious when multiple jobs execute concurrently.

For example, suppose an application has a SQL Server connection pool with a maximum size of 100 connections. If 80 long-running jobs each hold one connection, only 20 connections remain available to other application operations within that pool.

The application may experience connection acquisition delays even though many of those jobs are not actively querying the database.

A simplified execution model looks like this:

SQL
Background Job 1
      |
      +---- Open Connection
      |
      +---- Read Orders
      |
      +---- Call External API (2 minutes)
      |
      +---- Update Database
      |
      +---- Close Connection

Background Job 2
      |
      +---- Open Connection
      |
      +---- Process Records
      |
      +---- Wait for Another Service
      |
      +---- Update Database
      |
      +---- Close Connection

The important question is when the connection is opened and when it is released.

A database connection should generally be open only while the application is performing database operations.

It should not remain occupied while the application performs unrelated work.

Understand Connection Pooling in ADO.NET

Opening a physical database connection involves network communication, authentication, and session initialization. Repeating these operations for every database query would introduce unnecessary overhead.

ADO.NET uses connection pooling to reduce this cost.

Connection pooling maintains a collection of reusable physical connections.

When an application opens a connection, the database driver checks whether an appropriate connection is available in the pool.

If one is available, it is reused. Otherwise, the driver may create a new physical connection, provided the pool has not reached its configured maximum.

When the application closes or disposes the logical connection, the physical connection is normally returned to the pool.

Consider this example using Microsoft.Data.SqlClient:

C#
using Microsoft.Data.SqlClient;

public async Task UpdateOrderAsync(
    string connectionString,
    int orderId,
    CancellationToken cancellationToken)
{
    await using var connection =
        new SqlConnection(connectionString);

    await connection.OpenAsync(cancellationToken);

    await using var command = connection.CreateCommand();

    command.CommandText = """
        UPDATE Orders
        SET Status = @Status
        WHERE Id = @OrderId
        """;

    command.Parameters.AddWithValue("@Status", "Completed");
    command.Parameters.AddWithValue("@OrderId", orderId);

    await command.ExecuteNonQueryAsync(cancellationToken);
}

When the method finishes, the connection is disposed and returned to the pool.

This does not necessarily close the underlying physical database connection. The driver can reuse it for another operation.

This is why opening and disposing logical connections around individual database operations is generally a good practice.

Connection pooling is enabled by default in Microsoft.Data.SqlClient.

It is important to distinguish connection pooling from keeping a connection permanently open. A properly disposed connection can still benefit from pooling without remaining checked out for the entire lifetime of a background job.

Avoid Holding a Database Connection During External Operations

One of the most common mistakes in background processing is combining database operations and external API calls inside a single connection lifetime.

Consider the following implementation:

C#
public async Task ProcessOrderAsync(
    int orderId,
    CancellationToken cancellationToken)
{
    await using var connection =
        new SqlConnection(_connectionString);

    await connection.OpenAsync(cancellationToken);

    var order = await LoadOrderAsync(
        connection,
        orderId,
        cancellationToken);

    var paymentResult = await _paymentService
        .ProcessPaymentAsync(order, cancellationToken);

    await UpdateOrderStatusAsync(
        connection,
        orderId,
        paymentResult,
        cancellationToken);
}

The connection remains open while the payment service executes.

If the external service takes 30 seconds to respond, the database connection remains checked out for those 30 seconds.

This is unnecessary because the application does not need the database connection while waiting for the payment service.

A better implementation separates the database operations:

C#
public async Task ProcessOrderAsync(
    int orderId,
    CancellationToken cancellationToken)
{
    var order = await LoadOrderAsync(
        orderId,
        cancellationToken);

    var paymentResult = await _paymentService
        .ProcessPaymentAsync(order, cancellationToken);

    await UpdateOrderStatusAsync(
        orderId,
        paymentResult,
        cancellationToken);
}

Each database method manages its own connection.

For example:

C#
private async Task<Order> LoadOrderAsync(
    int orderId,
    CancellationToken cancellationToken)
{
    await using var connection =
        new SqlConnection(_connectionString);

    await connection.OpenAsync(cancellationToken);

    // Execute the order query and return the result.
    return await GetOrderFromDatabaseAsync(
        connection,
        orderId,
        cancellationToken);
}

The connection is released before the external payment operation begins.

The application then opens another logical connection when it needs to update the order.

Because connection pooling is enabled, the second operation can reuse a physical connection without requiring a completely new database login.

Use Short-Lived DbContext Instances in Background Services

Entity Framework Core introduces another important lifetime consideration.

In ASP.NET Core applications, AddDbContext registers a DbContext as a scoped service by default.

This works well for ordinary HTTP requests because a request typically represents one unit of work.

Background services have a different lifecycle.

A BackgroundService is generally registered as a singleton. Injecting a scoped DbContext directly into a singleton service can create lifetime problems.

It can also cause the same DbContext instance to remain alive for much longer than intended.

Consider this registration:

C#
builder.Services.AddDbContext<ApplicationDbContext>(
    options =>
        options.UseSqlServer(connectionString));

builder.Services.AddHostedService<OrderProcessor>();

The following implementation should be avoided:

C#
public class OrderProcessor : BackgroundService
{
    private readonly ApplicationDbContext _context;

    public OrderProcessor(ApplicationDbContext context)
    {
        _context = context;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var orders = await _context.Orders
                .Where(x => x.Status == "Pending")
                .ToListAsync(stoppingToken);

            // Process orders...

            await Task.Delay(
                TimeSpan.FromMinutes(1),
                stoppingToken);
        }
    }
}

The problem is that the DbContext is retained by the long-lived background service.

Its change tracker can accumulate entities, and its lifetime no longer represents a short database unit of work.

A better approach is to create a dependency injection scope for each processing iteration or use IDbContextFactory to create individual context instances.

Use IDbContextFactory for Long Running Jobs

EF Core provides IDbContextFactory for scenarios where the application needs explicit control over DbContext creation and disposal.

Register the factory in Program.cs:

C#
builder.Services.AddDbContextFactory<ApplicationDbContext>(
    options =>
        options.UseSqlServer(connectionString));

builder.Services.AddHostedService<OrderProcessor>();

The DbContext must accept DbContextOptions:

C#
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(
        DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Order> Orders => Set<Order>();
}

The background service can now create a context whenever it needs to perform database work.

C#
public class OrderProcessor : BackgroundService
{
    private readonly IDbContextFactory<ApplicationDbContext>
        _contextFactory;

    private readonly ILogger<OrderProcessor> _logger;

    public OrderProcessor(
        IDbContextFactory<ApplicationDbContext> contextFactory,
        ILogger<OrderProcessor> logger)
    {
        _contextFactory = contextFactory;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                List<Order> orders;

                await using (var context =
                    await _contextFactory.CreateDbContextAsync(
                        stoppingToken))
                {
                    orders = await context.Orders
                        .AsNoTracking()
                        .Where(x => x.Status == "Pending")
                        .OrderBy(x => x.Id)
                        .Take(100)
                        .ToListAsync(stoppingToken);
                }

                foreach (var order in orders)
                {
                    await ProcessOrderAsync(
                        order,
                        stoppingToken);
                }

                await Task.Delay(
                    TimeSpan.FromSeconds(10),
                    stoppingToken);
            }
            catch (OperationCanceledException)
                when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    ex,
                    "Error while processing pending orders.");

                await Task.Delay(
                    TimeSpan.FromSeconds(15),
                    stoppingToken);
            }
        }
    }

    private async Task ProcessOrderAsync(
        Order order,
        CancellationToken cancellationToken)
    {
        // Perform external or application processing here.
        await Task.CompletedTask;
    }
}

There are several important decisions in this implementation.

First, the context is created only when the service needs to query the database.

Second, the context is disposed immediately after retrieving the required records.

Third, AsNoTracking is used because the retrieved entities are read-only in this operation.

Finally, the service processes the orders without retaining the original DbContext.

This pattern keeps the DbContext lifetime short and avoids carrying its tracked entities through the entire background operation.

If the application needs to update an order, it can create another context for that update.

Understand the Difference Between DbContext Pooling and Connection Pooling

These two features are often confused because both involve reusing resources.

However, they solve different problems.

Connection pooling belongs to the database driver. It reuses physical database connections.

DbContext pooling belongs to Entity Framework Core. It reuses DbContext instances to reduce the cost of creating and initializing them.

FeatureConnection poolingDbContext pooling
Managed byDatabase driverEntity Framework Core
ReusesPhysical database connectionsDbContext instances
Main purposeReduce connection establishment overheadReduce context initialization overhead
ConfigurationProvider-specific connection settingsAddDbContextPool or AddPooledDbContextFactory
Resource lifetimeConnection checkout and returnContext checkout and return

For example, EF Core supports pooled context registration:

C#
builder.Services.AddPooledDbContextFactory<ApplicationDbContext>(
    options =>
        options.UseSqlServer(connectionString),
    poolSize: 128);

The poolSize parameter controls the maximum number of DbContext instances retained by the EF Core context pool.

It does not configure the maximum number of database connections.

Even when a DbContext is pooled, EF Core generally opens the database connection when an operation requires it and closes it afterward, returning it to the underlying driver's connection pool.

For background jobs, context pooling can be useful when context creation becomes a measurable performance concern.

However, it is not necessary for every application.

Be especially careful with manually managed connection state, custom interceptors, and mutable context-level configuration. EF Core resets its own context state when returning a context to its pool, but it does not automatically reset every piece of state managed by the underlying database driver.

Always close manually opened connections before returning a pooled context.

Configure the Connection Pool According to the Workload

Even when connections are disposed correctly, an application can still experience connection pool exhaustion.

One reason is that too many operations may be requesting connections simultaneously.

Microsoft.Data.SqlClient provides connection string options for controlling the pool.

For example:

Code
Server=localhost;
Database=OrdersDb;
User Id=appuser;
Password=your-password;
Max Pool Size=100;
Min Pool Size=5;
Connect Timeout=30;

Important settings include:

Max Pool Size defines the maximum number of physical connections in the pool. The default is 100.

Min Pool Size defines the minimum number of connections retained in the pool after it has been created.

Connect Timeout controls how long the application waits when attempting to establish a connection, including waiting for an available pooled connection.

Load Balance Timeout, also known as Connection Lifetime, controls the maximum age of a connection when it is returned to the pool. Its default value is zero, which disables age-based removal.

Increasing Max Pool Size is not always the right solution.

Suppose an application has 10 Cloud Run or container instances, and each instance can create a pool with a maximum of 100 connections.

The application could potentially request up to 1,000 connections across those instances, assuming the same pool configuration is used in each process.

The database must be able to handle the total demand.

Before increasing the pool size, investigate whether connections are being held too long, transactions are remaining open, or background jobs are running with excessive concurrency.

A smaller number of well-managed connections is often more effective than a large pool filled with long-running operations.

Process Large Datasets in Batches

Another common problem occurs when a background job loads thousands or millions of records into memory and processes them in one operation.

For example:

C#
var orders = await context.Orders
    .Where(x => x.Status == "Pending")
    .ToListAsync(cancellationToken);

If the query returns a very large result set, the application may consume significant memory and keep database resources occupied while processing the data.

A better approach is to process records in batches.

C#
public async Task ProcessPendingOrdersAsync(
    CancellationToken cancellationToken)
{
    const int batchSize = 100;

    while (!cancellationToken.IsCancellationRequested)
    {
        List<Order> orders;

        await using (var context =
            await _contextFactory.CreateDbContextAsync(
                cancellationToken))
        {
            orders = await context.Orders
                .AsNoTracking()
                .Where(x => x.Status == "Pending")
                .OrderBy(x => x.Id)
                .Take(batchSize)
                .ToListAsync(cancellationToken);
        }

        if (orders.Count == 0)
        {
            break;
        }

        foreach (var order in orders)
        {
            await ProcessOrderAsync(
                order,
                cancellationToken);
        }
    }
}

This example demonstrates the batch-processing approach, but it needs an additional production consideration: records should be claimed or marked as being processed before multiple workers can select the same batch.

Otherwise, concurrent workers may retrieve and process the same pending records.

A production implementation can use database transactions, status transitions, row-level locking, or a queue-based design to ensure that each work item is claimed safely.

For large datasets, keyset pagination is generally preferable to repeatedly using large Skip values.

For example, the application can remember the last processed order ID and query records greater than that value.

This reduces the cost of navigating increasingly large result sets.

Keep Database Transactions Short

Database transactions are another reason connections may remain unavailable longer than necessary.

Consider a job that starts a transaction, updates an order, calls an external payment service, and then commits the transaction.

C#
await using var transaction =
    await context.Database.BeginTransactionAsync(
        cancellationToken);

order.Status = "Processing";

await context.SaveChangesAsync(cancellationToken);

await _paymentService.ProcessPaymentAsync(
    order,
    cancellationToken);

order.Status = "Completed";

await context.SaveChangesAsync(cancellationToken);

await transaction.CommitAsync(cancellationToken);

The transaction remains active while the external payment service executes.

This can hold database locks and consume resources unnecessarily. It also creates a difficult failure scenario if the payment service succeeds but the database transaction fails.

A better approach is to keep database transactions focused on database operations.

For workflows involving external systems, consider patterns such as:

  • Persisting an operation request before calling the external service.
  • Using an idempotency key for external operations.
  • Updating the operation status after receiving the result.
  • Using an outbox pattern to coordinate database changes and message publication.
  • Implementing retry and reconciliation logic for incomplete operations.

A short database transaction should establish the state needed for the next operation, commit, and release its resources before external processing begins.

This is especially important for payment, order processing, and financial workflows.

Handle Connection Failures and Transient Database Errors

Long-running jobs are more likely to encounter temporary infrastructure problems simply because they execute for longer periods.

Examples include:

  • Temporary database unavailability.
  • Network interruptions.
  • Database failover.
  • Connection timeouts.
  • Deadlocks.
  • Temporary service throttling.

Applications should distinguish between transient failures and permanent errors.

For SQL Server, EF Core supports connection resiliency through the EnableRetryOnFailure configuration.

C#
builder.Services.AddDbContextFactory<ApplicationDbContext>(
    options =>
        options.UseSqlServer(
            connectionString,
            sqlOptions =>
                sqlOptions.EnableRetryOnFailure(
                    maxRetryCount: 5,
                    maxRetryDelay: TimeSpan.FromSeconds(10),
                    errorNumbersToAdd: null)));

The provider can retry operations that it identifies as transient failures.

However, retrying a database operation does not automatically make an entire business workflow safe to repeat.

For example, if an external payment succeeds but the application loses the response before recording the result, repeating the payment operation could charge the customer twice.

Use idempotency keys, durable job state, and appropriate transaction boundaries to make retries safe.

Also, execution strategies can retry database operations that fail transiently. When using an explicit transaction with a retrying execution strategy, the transaction must be executed as a retriable unit using the execution strategy's supported pattern.

Do not wrap arbitrary business operations in automatic retries without considering their side effects.

Monitor Connection Pool Health

Connection pool problems are easier to fix when the application can detect them before users experience failures.

For SQL Server applications using Microsoft.Data.SqlClient, monitor:

  • Active database connections.
  • Connection acquisition time.
  • Connection open and close rates.
  • Connection timeout exceptions.
  • Query execution duration.
  • Transaction duration.
  • Number of concurrent background jobs.
  • Database connection count at the server level.

.NET also exposes diagnostic information through the Microsoft.Data.SqlClient EventSource and related metrics.

These can help identify connection pool pressure and connection lifecycle problems.

For SQL Server, database administrators can inspect active sessions using:

SQL
SELECT
    session_id,
    status,
    login_name,
    host_name,
    program_name,
    last_request_start_time,
    last_request_end_time
FROM sys.dm_exec_sessions
WHERE is_user_process = 1
ORDER BY last_request_start_time DESC;

This query provides visibility into user sessions and their recent activity.

It does not directly identify which application method is holding a connection, but it can help investigate unusually long-lived sessions.

Application-side logging should also include a job identifier, operation name, and elapsed time.

For example, a background job can log when it opens a connection, completes a query, and finishes a database transaction.

Avoid logging credentials, connection strings, or sensitive customer information.

Common Mistakes to Avoid

Several implementation mistakes can gradually create database connection problems.

Keeping one SqlConnection open for an entire background job prevents the pool from reusing that connection while the job performs unrelated work.

Injecting a scoped DbContext directly into a singleton BackgroundService creates an inappropriate lifetime relationship.

Creating a new DbContext for every individual database statement can add unnecessary overhead. Prefer a context that represents a meaningful unit of work, while keeping that unit reasonably short.

Increasing Max Pool Size without investigating connection leaks can hide the problem temporarily and increase pressure on the database.

Running too many background jobs simultaneously can overwhelm the database even when every connection is disposed correctly.

Finally, using a long-running transaction around external API calls can hold locks and database resources unnecessarily.

These problems are best addressed through deliberate resource management rather than simply increasing timeouts or connection limits.

Summary

Long-running ASP.NET Core jobs need careful database connection management because they execute outside the short lifecycle of ordinary HTTP requests.

ADO.NET connection pooling allows applications to reuse physical database connections without keeping logical connections open indefinitely. Entity Framework Core provides IDbContextFactory and dependency injection scopes to create short-lived DbContext instances for background processing.

The most important practices are to open connections immediately before database operations, dispose them when those operations finish, avoid holding connections during external calls, process large datasets in batches, and keep database transactions short.

Connection pool settings should be configured according to the total application workload, not increased simply because connection timeouts occur.

With proper connection lifetimes, controlled job concurrency, safe retries, and connection monitoring, background services can process large workloads without unnecessarily exhausting database resources.