Confirming service instance-per-request and thread safety of base.Response

Hi,

I’d like to confirm my understanding of ServiceStack’s service lifecycle regarding thread safety.

Given this service:

csharp

public class HelloServices : Service
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(HelloServices));

    private object? Unauthorized(string logMessage)
    {
        Log.Warn(logMessage);
        base.Response.StatusCode = 401;
        return null;
    }

    public object Get(Hello request)
    {
        return new HelloResponse { Result = $"Hello, {request.Name}!" };
    }

    public object Get(HelloUnauthorized request)
    {
        return Unauthorized("Invalid credentials");
    }
}

My understanding:

  1. ServiceStack creates a new service instance per request, so base.Response is always scoped to that specific request. Two concurrent requests would each have their own instance, and calling Unauthorized() on one cannot affect the other’s response.
  2. More generally, any non-static method or property on the service class is request-scoped — there’s no shared state between concurrent requests unless I explicitly introduce it (e.g., via static fields,etc.).

Is this correct?

We have a production API and want to refactor some logic into private helper methods like Unauthorized() above. Before doing so, I want to confirm there’s no risk of cross-request contamination under concurrent load.

Thanks.

That’s correct 2 concurrent requests execute 2 independent Service instances and each have their own separate Request/Response contexts. Same applies to per instance (i.e. non-static) fields.

Just like the rest of .NET, the object instances aren’t threadsafe, i.e. you shouldn’t spawn a separate background thread access the same Service Instance / Request Context whilst the Request Worker thread is still executing it.

1 Like