Azure Functions makes it easy to write small pieces of code that respond to HTTP requests, queue messages, timers, and other events. A function can look simple enough that developers sometimes treat it like a normal method that runs once, finishes its work, and disappears.

That assumption can cause problems when state is stored incorrectly.

An Azure Function application can process multiple invocations at the same time. Depending on the hosting model, the same worker process may handle many invocations before it is restarted. This means a static field, singleton service, cached object, or mutable global variable can remain in memory and become visible to later invocations.

The result can be difficult-to-reproduce bugs.

One customer may receive another customer's data. A counter may have an unexpected value. A cached object may contain stale information. Two requests may modify the same collection at the same time.

These problems are especially confusing because the code may work perfectly during local testing when requests arrive one at a time.

This article explains why invocation state can leak between Azure Function executions, which types of state are risky, and how to design functions so that each invocation remains independent.

Why Azure Functions Can Run Multiple Invocations in the Same Process

Consider a simple HTTP-triggered function:

C#
[Function("ProcessOrder")]
public async Task<HttpResponseData> Run(
    [HttpTrigger(AuthorizationLevel.Function, "post")]
    HttpRequestData request)
{
    // Process order

    return request.CreateResponse(HttpStatusCode.OK);
}

It is tempting to think about this function like a regular method:

Code
Request
   ↓
Function starts
   ↓
Function finishes
   ↓
Everything disappears

That is not how the underlying runtime necessarily behaves.

A worker process can remain alive and handle another invocation later:

Code
Worker Process
      │
      ├── Invocation 1
      ├── Invocation 2
      ├── Invocation 3
      ├── Invocation 4
      └── Invocation 5

The process can also handle multiple invocations concurrently.

This distinction matters because memory belonging to the process can survive after one function invocation has completed.

If application code stores mutable data at process scope, another invocation may see that data.

The Most Common Problem: Static Mutable State

Consider this example:

Java
public static class OrderCache
{
    public static List<int> Orders = new();
}

A function might use it like this:

C#
[Function("AddOrder")]
public HttpResponseData Run(
    [HttpTrigger(AuthorizationLevel.Function, "post")]
    HttpRequestData request)
{
    OrderCache.Orders.Add(123);

    var response = request.CreateResponse(HttpStatusCode.OK);
    response.WriteString($"Orders: {OrderCache.Orders.Count}");

    return response;
}

The developer may expect the list to represent the current request.

It does not.

The list belongs to the process, not to the individual invocation.

If the function runs five times, the list can contain data from previous invocations:

Code
Invocation 1 → [123]
Invocation 2 → [123, 456]
Invocation 3 → [123, 456, 789]

The exact lifetime depends on the worker process and hosting behavior, but the important point is that the static object is not invocation-scoped.

Why This Bug Is Easy to Miss

This type of problem often survives development testing.

Suppose you run one request:

Code
POST /api/order

The application starts, processes the request, and returns the expected result.

You run another request after some time.

Everything still appears normal.

The problem becomes visible when multiple users send requests concurrently.

For example:

SQL
User A → Order 1001
User B → Order 1002
User C → Order 1003

If shared state is used incorrectly, the execution can become:

Code
User A → writes 1001
User B → reads 1001
User C → reads 1001 + 1002

Now the problem is no longer an obvious application crash.

It becomes a data correctness issue.

Instance Fields Can Also Be Dangerous

Developers sometimes avoid static variables and assume instance fields are always safe.

That assumption is also incomplete.

Consider:

C#
public class OrderFunction
{
    private readonly List<int> _orders = new();

    public OrderFunction()
    {
    }

    [Function("Order")]
    public HttpResponseData Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")]
        HttpRequestData request)
    {
        _orders.Add(1001);

        var response = request.CreateResponse(HttpStatusCode.OK);
        response.WriteString(_orders.Count.ToString());

        return response;
    }
}

Whether an instance is reused depends on how the function worker manages the function class.

The important design principle is simpler:

Do not use mutable instance state as a place to store data that belongs to one invocation.

If the value belongs to the request, keep it inside the method or pass it explicitly through the call chain.

What Should Be Invocation State?

Suppose a request contains an order ID:

Code
{
  "orderId": 1001
}

The order ID should normally exist as local data:

C#
[Function("ProcessOrder")]
public async Task<HttpResponseData> Run(
    [HttpTrigger(AuthorizationLevel.Function, "post")]
    HttpRequestData request)
{
    var orderId = await ReadOrderIdAsync(request);

    await ProcessOrderAsync(orderId);

    var response = request.CreateResponse(HttpStatusCode.OK);
    await response.WriteAsJsonAsync(new
    {
        orderId,
        status = "Processed"
    });

    return response;
}

Here, orderId belongs to the invocation.

Another request gets another orderId.

There is no shared mutable memory involved.

Singleton Services Need Special Attention

Dependency injection makes this problem less obvious.

Suppose you register a service as a singleton:

Code
services.AddSingleton<OrderContext>();

Then:

C#
public class OrderContext
{
    public int OrderId { get; set; }
}

A function injects it:

C#
public class OrderFunction
{
    private readonly OrderContext _context;

    public OrderFunction(OrderContext context)
    {
        _context = context;
    }

    [Function("Order")]
    public HttpResponseData Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")]
        HttpRequestData request)
    {
        _context.OrderId = 1001;

        // Process order

        return request.CreateResponse(HttpStatusCode.OK);
    }
}

This creates a serious problem.

A singleton instance can be shared by multiple invocations.

Imagine:

Code
Invocation A
    ↓
OrderId = 1001

Invocation B
    ↓
OrderId = 2002

Invocation A
    ↓
Reads OrderId = 2002

The code may look completely reasonable during review, but the lifetime of the object does not match the lifetime of the data.

Singleton Does Not Mean Thread Safe

Another common mistake is assuming that registering a service as a singleton automatically makes it safe for concurrent requests.

It does not.

Consider:

C#
public class RequestCounter
{
    public int Count { get; set; }
}

If this object is registered as a singleton:

Code
services.AddSingleton<RequestCounter>();

multiple invocations may access:

Code
counter.Count++;

at the same time.

This operation is not simply one indivisible action.

Conceptually, it is:

Code
Read Count
Add 1
Write Count

Two invocations can interleave those operations.

For example:

Code
Invocation A → reads 10
Invocation B → reads 10
Invocation A → writes 11
Invocation B → writes 11

The expected value was 12, but the result is 11.

Even if thread synchronization is added, that does not automatically make the design correct. You still need to determine whether the data should be shared in the first place.

Use Scoped Services Carefully

A scoped service is generally a better fit when the dependency represents data associated with one invocation.

For example:

Code
services.AddScoped<OrderContext>();

Then:

C#
public class OrderContext
{
    public int OrderId { get; set; }
}

The function can use it as part of the invocation's dependency graph.

However, developers should still avoid treating scoped state as a general-purpose storage mechanism.

If the state needs to survive after the function invocation, use an external durable store.

Transient Services Are Not a Replacement for Good State Design

You may also register a service as transient:

Code
services.AddTransient<OrderProcessor>();

This creates a new service instance when requested.

That can be useful for stateless processing components.

However, changing a service lifetime does not solve every state-management problem.

For example, this is still a bad design:

Java
public class OrderProcessor
{
    private static List<int> Orders = new();
}

The service itself may be transient, but the static list is still shared.

The lifetime of the data matters more than the lifetime of the wrapper class.

Avoid Using Static Collections as Caches

A common pattern is:

Code
private static readonly Dictionary<string, Product> Products = new();

It may appear to improve performance.

But this introduces several concerns:

  • Data can become stale.

  • Multiple invocations can modify the collection.

  • Memory usage can grow.

  • Concurrent access can cause errors.

  • Different worker processes may have different cache contents.

  • Restarting the worker removes the cache.

  • Scaling out creates multiple independent copies.

For example:

Code
Worker 1
   ProductCache = A, B, C

Worker 2
   ProductCache = A, B

Worker 3
   ProductCache = A, B, C, D

There is no guarantee that all workers share the same in-memory state.

If the application needs a shared cache, use a distributed cache such as Azure Cache for Redis or another appropriate external storage system.

In-Memory Cache Is Not Distributed State

Suppose you store a session token in memory:

Code
private static Dictionary<string, string> Sessions = new();

A request reaches Worker 1:

Code
User → Worker 1
       Session found

Later, another request reaches Worker 2:

Code
User → Worker 2
       Session not found

The user may appear to be logged out even though nothing was removed from the application.

This happens because the two workers have different memory.

The same issue applies to:

  • Session data

  • Shopping carts

  • Feature flags

  • Rate-limit counters

  • Temporary workflow state

  • Authentication information

  • Background processing state

If the state must be shared between workers, keep it outside the process.

Store Shared State Externally

For state that must survive across invocations, use an appropriate external store.

For example, Azure Table Storage can hold durable application state:

Code
await tableClient.AddEntityAsync(new OrderState
{
    PartitionKey = "orders",
    RowKey = orderId.ToString(),
    Status = "Processing"
});

A database may be appropriate for transactional state:

Code
Function
   ↓
Database
   ↓
Persistent state

Redis can be appropriate for fast shared cache data:

Code
Function
   ↓
Redis
   ↓
Shared cache

The important distinction is:

Code
Local memory
    ↓
Temporary process state

External storage
    ↓
Shared application state

Do Not Store Request-Specific Data in Static Variables

Consider this code:

Code
public static string CurrentUserId;

Then:

Code
CurrentUserId = userId;

This creates a race between invocations.

Instead:

Code
var currentUserId = userId;

Pass the value to the methods that need it:

Code
await ProcessOrderAsync(currentUserId, orderId);

This makes the data flow explicit.

It also makes the code easier to test.

Use Immutable Objects When Sharing Is Necessary

Sometimes shared state is legitimate.

For example, an application may have configuration data that does not change during execution.

In such cases, immutable data is safer than mutable state.

Instead of:

Code
public static Dictionary<string, string> Settings;

consider an immutable representation:

C#
public static IReadOnlyDictionary<string, string> Settings =
    new Dictionary<string, string>
    {
        ["region"] = "eastus"
    };

The important part is not the interface itself.

IReadOnlyDictionary does not magically make the underlying dictionary immutable.

The actual object should be created and managed so that application code cannot modify it unexpectedly.

Be Careful With Async Code

State bugs become even harder to diagnose when asynchronous operations are involved.

Consider:

C#
private static string _currentOrderId;

public async Task ProcessAsync(string orderId)
{
    _currentOrderId = orderId;

    await Task.Delay(1000);

    Console.WriteLine(_currentOrderId);
}

Suppose two invocations run concurrently:

Code
Invocation A → Order 1001
Invocation B → Order 2002

The sequence can become:

Code
A → _currentOrderId = 1001
B → _currentOrderId = 2002
A → resumes
A → reads 2002

The asynchronous delay makes the race easier to expose.

The solution is to keep the value local:

C#
public async Task ProcessAsync(string orderId)
{
    var currentOrderId = orderId;

    await Task.Delay(1000);

    Console.WriteLine(currentOrderId);
}

Now each invocation has its own local variable.

Static Fields That Are Safe

Not every static field is automatically dangerous.

A static immutable value can be perfectly reasonable:

Code
private static readonly string ApplicationName = "OrderProcessor";

Another example is a stateless helper:

C#
public static class OrderValidator
{
    public static bool IsValid(int orderId)
    {
        return orderId > 0;
    }
}

The concern is mutable shared state.

A useful rule is:

Code
Static + mutable + invocation-specific
                    ↓
                 Avoid

While:

Code
Static + immutable + application-wide
                    ↓
              Usually safe

Even then, review the object's thread-safety characteristics before using it across concurrent invocations.

Testing for State Leakage

A single request is not enough to test state isolation.

Create a test that sends multiple requests concurrently.

For example:

Code
var tasks = Enumerable.Range(1, 100)
    .Select(i => client.PostAsJsonAsync(
        "/api/order",
        new { orderId = i }));

await Task.WhenAll(tasks);

Then verify that each response contains the correct request data.

You are looking for behavior such as:

Code
Request 1 → Response 1
Request 2 → Response 2
Request 3 → Response 3

and not:

Code
Request 1 → Response 3
Request 2 → Response 1
Request 3 → Response 2

For shared counters, caches, collections, and singleton services, concurrency testing is particularly important.

A Practical Code Review Checklist

When reviewing an Azure Function, search for:

Code
static
Singleton
Dictionary
List
Cache
CurrentUser
CurrentRequest
Session
State
Counter
LastRequest

These terms do not automatically mean there is a bug.

They are useful places to investigate.

Ask these questions:

  1. Who owns this data?

  2. How long should the data live?

  3. Can two invocations access it simultaneously?

  4. Can another worker process access it?

  5. Does the data need to survive a restart?

  6. Does the data belong to one request or the entire application?

  7. Is the object thread-safe?

  8. What happens when the application scales out?

These questions often expose state-related problems before they reach production.

Common Mistakes

Assuming One Function Invocation Equals One Process

An invocation is a unit of execution, not necessarily a dedicated operating-system process.

Multiple invocations can execute through the same worker process.

Using Singleton Services for Convenience

A singleton is not a general-purpose place to store request data.

Use singleton services primarily for truly application-wide, thread-safe, reusable components.

Using Static Collections as Databases

A static collection is memory.

It is not a database, distributed cache, or durable queue.

Testing Only One Request

Sequential local testing may never expose a concurrency problem.

Test concurrent invocations.

Forgetting Scale-Out

Even if shared memory appears to work with one worker, scaling out creates multiple processes.

A memory-based solution can then produce inconsistent results.

Best Practices

Keep invocation-specific data local whenever possible.

Pass data explicitly between methods instead of placing it into shared fields.

Use dependency injection for services, but choose the service lifetime based on the actual state requirements.

Use external storage for state that needs to survive between invocations.

Use a distributed cache when multiple workers need access to the same cached data.

Avoid mutable static collections.

Make shared components thread-safe when shared state is genuinely required.

Test functions under concurrent execution rather than only sequential execution.

Monitor production behavior for unusual data mixing, race conditions, and inconsistent responses.

Final Thoughts

Azure Functions can scale and execute many invocations concurrently, so application code should not assume that memory belongs to one request.

The safest approach is to make invocation-specific state explicit and local. Request data should normally stay within the invocation and be passed to the services that need it.

For state that must survive beyond the invocation or be shared between multiple workers, use an external service such as a database, storage system, or distributed cache.

The key question during development is not simply "Does this variable work?"

It is:

"Who else can see this variable, and how long does it live?"

Once that question becomes part of the code review process, many difficult Azure Functions concurrency bugs become much easier to prevent.