WCF – Cross-machine semaphore with WCF

Came across an interesting question on StackOverflow on how one might be able to throttle the number of requests across multiple servers running the same WCF service. So for instance, if you have 3 servers sitting behind a load balancer and for one reason or another you can only allow 5 requests to be made against the service at any moment in time and any subsequent requests need to be queued until one of the previous requests finish.

For those of you familiar with the programming concept of a semaphore, you might see that the above requirement describes a semaphore which applies across multiple machines. A quick search on Google for ‘cross-machine semaphore’ reveals several implementations of such system using memcached.

Naturally, a distributed cache is a good way to go about implementing a cross-machine semaphore IF you are already using it for something else. Otherwise the overhead and cost of running a distributed cache cluster purely for the sake of a cross-machine semaphore makes this approach a no-go for most of us..

Instead, you could easily implement a semaphore service to provide the same functionality to multiple WCF clients as the bog-standard Semaphore class do to multiple threads. Such a service might look something like this:

[ServiceContract]
public interface ISemaphorService
{
    [OperationContract]
    void Acquire();

    [OperationContract]
    void Release();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class SemaphoreService
{
    private readonly static Semaphore Pool = new Semaphore(5, 5);

    public void Acquire()
    {
        Pool.WaitOne();
    }

    public void Release()
    {
        Pool.Release();
    }
}

This approach will introduce a single point of failure as for semaphore service to work correctly it’ll need to be running on a single machine. If you were to use this approach you should have build up some infrastructure around it so that you can recover swiftly if and when the server running the semaphore service goes down.

In terms of the client code you should make sure that Release is called for every Acquire call, so would be a good idea to put a try-finally block around it:

var client = new SemaphoreServiceClient();

try
{
    // acquire the semaphore before processing the request
    client.Acquire();

    // process request
    ...
}
finally
{
    // always remember the release the semaphore
    client.Release();
}


Yan Cui

I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.

You can contact me via Email, Twitter and LinkedIn.

Hire me.