Here Be Monsters – Message broker that links all things

In our MMORPG title Here Be Monsters, we offer the players a virtual world to explore where they can visit towns and spots; forage fruits and gather insects and flowers; tend to farms and animals in their homesteads; make in-game buddies and help each other out; craft new items using things they find in their travels; catch and cure monsters corrupted by the plague; help out troubled NPCs and aid the Ministry of Monsters in its struggle against the corruption, and much more!

All and all, there are close to a hundred distinct actions that can be performed in the game and more are added as the game expands. At the very centre of everything you do in the game, is a quest and achievements system that can tap into all these actions and reward you once you’ve completed a series of requirements.


The Challenge

However, such a system is complicated by the snowball effect that can occur following any number of actions. The following animated GIF paints an accurate picture of a cyclic set of chain reactions that can occurred following a simple action:


In this instance,

  1. catching a Gnome awards EXP, gold and occasionally loot drops, in addition to fulfilling any requirement for catching a gnome;
  2. getting the item as loot fulfils any requirements for you to acquire that item;
  3. the EXP and gold awarded to the player can fulfil requirements for acquiring certain amounts of EXP or gold respective;
  4. the EXP can allow the player to level up;
  5. levelling up can then fulfil a requirement for reaching a certain level as well as unlocking new quests that were previously level-locked;
  6. levelling up can also award you with items and gold and the cycle continues;
  7. if all the requirements for a quest are fulfilled then the quest is complete;
  8. completing a quest will in turn yield further rewards of EXP, gold and items and restarts the cycle;
  9. completing a quest can also unlock follow-up quests as well as fulfilling quest-completion requirements.


The same requirements system is also in place for achievements, which represent longer term goals for players to play for (e.g. catch 500 spirit monsters). The achievement and quest systems are co-dependent and feeds into each other, many of the milestone achievements we currently have in the game depend upon quests to be completed:


Technically there is a ‘remote’ possibility of deadlocks but right now it exists only as a possibility since new quest/achievement contents are generally played through many many times by many people involved in the content generation process to ensure that they are fun, achievable and that at no point will the players be left in a state of limbo.


This cycle of chain reactions introduces some interesting implementation challenges.

For starters, the different events in the cycle (levelling up, catching a monster, completing a quest, etc.) are handled and triggered from different abstraction layers that are loosely coupled together, e.g.

  • Level controller encapsulates all logic related to awarding EXP and levelling up.
  • Trapping controller encapsulates all logic related to monster catching.
  • Quest controller encapsulates all logic related to quest triggering, progressing and completions.
  • Requirement controller encapsulates all logic related to managing the progress of requirements.
  • and many more..

Functionally, the controllers form a natural hierarchy whereby higher-order controllers (such as the trapping controller) depend upon lower-order controllers (such as level controller) because they need to be able award players with EXP and items etc. However, in order to facilitate the desired flow, theoretically all controllers will need to be able to listen and react to events triggered by all other controllers..


To make matter worse, there are also non-functional requirements which also requires the ability to tap into this rich and continuous stream of events, such as:

  • Analytics tracking – every action the player takes in the game is recorded along with the context in which they occurred (e.g. caught a gnome with the trap X, acquired item Z, completed quest Q, etc.)
  • 3rd party reporting – notify ad partners on key milestones to help them track and monitor the effectiveness of different ad campaigns
  • etc..


For the components that process this stream of events, we also wanted to make sure that our implementation is:

  1. strongly cohesive – code that are dealing with a particular feature (quests, analytics tracking, community goals, etc.) are encapsulated within the same module
  2. loosely coupled – code that deals with different features should not be directly dependent on each other and where possible they should exist completely independently

Since the events are generated and processed within the context of one HTTP request (the initial action from the user), the stream also have a lifetime that is scoped to the HTTP request itself.


And finally, in terms of performance, whilst it’s not a latency critical system (generally a round-trip latency of sub-1s is acceptable) we generally aim for a response time (between request reaching the server and the server sending back a response) of 50ms to ensure a good round-trip latency from the user’s perspective.

In practice though, the last-mile latency (from your ISP to you) has proven to be the most significant factor in determining the round-trip latency.


The Solution

After considering several approaches:

  • Vanilla .Net events
  • Reactive Extensions (Rx)
  • CEP platforms such as Esper or StreamInsight

we decided to go with a tailor-made solution for the problem at hand.

In this solution we introduced two abstractions:

  • Facts – which are special events for the purpose of this particular system, we call them facts in order to distinguish them from the events we record for analytics purpose already. A fact contains information about an action or a state change as well as the context in which it occurred, e.g. a CaughtMonster fact would contain information about the monster, the trap, the bait used, where in the world the action occurred, as well as the rewards the player received.
  • Fact Processor – a component which processes a fact.


As a request (e.g. to check our trap to see if we’ve caught a monster) comes in the designated request handler will first perform all the relevant game logic for that particular request, accumulating facts along the way from the different abstraction layers that have to work together to process this request.

At the end of the core game logic, the accumulated facts is then forwarded to each of the configured fact processors in turn. The fact processors might choose to process or ignore each of the facts.

In choosing to process a fact the fact processors can cause state changes or other interesting events to occur which results in follow-up facts to be added to the queue.



The system described above has the benefits of being:

  • Simple – easy to understand and reason with, easy to modularise, no complex orchestration logic or spaghetti code.
  • Flexible – easy to change information captured by facts and processing logic in fact processors
  • Extensible – easy to add new facts and/or fact processors into the system

The one big downside being that for the system to work it requires many types of facts which means it could potentially add to your maintenance overhead and requires lots of boilerplate class setup.


To address these potential issues, we turned to F#’s discriminated unions over standard .Net classes for its succinctness. For a small number of facts you can have something as simple as the following:


However, as we mentioned earlier, there are a lot of different actions that can be performed in Here Be Monsters and therefore many facts will be required to track those actions as well as the state changes that occur during those actions. The simple approach above is not a scalable solution in this case.

Instead, you could use a combination of marker interface and pattern matching to split the facts into a number of specialized discriminated union types.


Update  2014/07/28 : thank you to @johnazariah for bringing this up, the reason for choosing to use a marker interface rather than a hierarchical discriminated union in this case is because it makes interop with C# easier.

In C#, you can create the StateChangeFacts.LevelUp union clause above using the compiler generated StateChangeFacts.NewLevelUp static method but it’s not as readable as the equivalent F# code.

With a hierarchical DU the code will be even less readable, e.g. Fact.NewStateChange(StateChangeFacts.NewLevelUp(…))


To wrap things up, once all the facts are processed and we have dealt with the request in full we need to generate a response back to the client to report all the changes to the player’s state as a result of this request. To simplify the process of tracking these state changes and to keep the codebase maintainable we make use of a Context object for the current request (similar to HttpContext.Current) and make sure that each state change (e.g. EXP, energy, etc.) occurs in only one place in the codebase and that change is tracked at the point where it occurs.

At the end of each request, all the changes that has been collected is then copied from the current Context object onto the response object if it implements the relevant interface – for example, all the quest-related state changes are copied onto a response object if it implements the IHasQuestChanges interface.


Related Posts

F# – use Discriminated Unions instead of Classes

F# – extending Discriminated Unions using marker interfaces

Dart – implementing the Singleton pattern with factory constructors

In Dart there is an interesting language feature called ‘Factory Constructors’, which effectively allows you to override the default behaviour when using the new keyword – instead of always creating a new instance the factory constructor is merely required to return an instance of the class, the difference is important.

Factory constructors allow you to implement a number of techniques and patterns without altering code that consumes your class. For instance,

  • Singleton pattern which we will look at more closely.
  • Object pooling, a useful technique for reducing the amount of allocations (and its associated allocation cost and consequent GC pressure) in performance critical applications.
  • Flyweight pattern which is already discussed in more detail in this Idiomatic Dart article.

These are just 3 use cases that I can think of off the top of my head, please feel free to suggest any more that I have missed.

Problems with common Singleton pattern implementations

In other languages (well, the ones that I’m familiar with anyway!), in order to implement the Singleton pattern you have to ensure that the class’s constructor is not exposed publicly and that access to the singleton instance is done via a static Singleton property. Revered C#/Java developer Jon Skeet has a very good article on the various solutions one might adopt to implement the singleton pattern in C#.


These implementations require code that consumes your class to be aware of its implementation of the singleton pattern and create a vast blast radius throughout your application should you one day decide that the singleton pattern is no longer necessary/applicable.

For instance, if assumptions in your application change drastically (and they often do..) and you need to switch to the flyweight or another pattern instead to cater for changing requirements and/or assumptions.

Unintentional tight coupling

In the case of C# (where static members are not allowed on interfaces and abstract classes are un-constructible) the standard singleton pattern also create tight coupling to a concrete implementation where it’s seldom necessary.

You can, to some degree, work around this issue of tight coupling by introducing an IOC container as middle man between your class and its consumers, most IOC containers provide some mechanism for controlling object lifespans (transient, singleton, pooled, etc.). However, you now have tight coupling to the IOC container instead…

Singleton pattern with Factory constructors

You can implement the singleton pattern using factory constructors like this:

the key thing here is that any consuming code is completely oblivious to the fact that we have just implemented the singleton pattern. If we were to continue our mind later or forced to adopt a different pattern because of changing requirement, there will be trivial or no change on all the consuming code!


Idiomatic Dart – Factory constructors

Jon Skeet – Implementing the Singleton pattern in C#

Shlomo Swidler’s Many Cloud Design Patterns slides

This is so good I keep going back to it, so to save myself and you the hassle of searching for it every time I thought I’d share it here on my blog, enjoy! Smile

.Net Tips – Use Request and Response objects

We’ve all been there before, write a simple service with a simple method:

public interface IService
    int SimpleMethod(object param1);

As time goes by, the simple method gets more complicated, and the list of parameters grows and eventually simple method is overloaded to provide more variety and simple method is simple no more!

A simple solution to this is the Request-Response pattern, by encapsulating all the input and output values into request and response objects you will be able to:

  • solve the problem with growing parameters
  • have an easy way of providing multiple results
  • add input/output values incrementally

And you’ll be able to do all this without even changing the service contract!

public interface IService
    SimpleMethodResponse SimpleMethod(SimpleMethodRequest request);

public void SimpleMethodRequest
    public object Param1 { get; set; }

    public string Param2 { get; set; }

    public int Param3 { get; set; }


public void SimpleMethodResponse
    public bool Success { get; set; }

    public int? ErrorCode { get; set; }

    public string ErrorMessage { get; set; }


In addition, you can also create a hierarchy of request/response objects and consolidate your validation logic in validator classes or custom validation attractions (you can use PostSharp to write attributes that take care of the validation ‘aspect’ of your application).


API Design Patterns – Request/Response

Threading – Producer-Consumer Pattern

Having run into a bit of deadlocking issue while working on Bingo.Net I spent a bit of time reading into the Producer-Consumer pattern and here’s what I learnt which I hope you’ll find useful too.

AutoResetEvent and ManualResetEvent

To start off, MSDN has an introductory article on how to synchronize a producer and a consumer thread. It’s a decent starting point, however, as some of the comments pointed out the sample code is buggy and allows for a race condition to happen when the AutoResetEvent is reset in quick succession whilst the consumer thread is processing the previous reset.

The problem with the AutoResetEvent is that you can set an event that is already set which does not have any effect:


And just like that, the Consumer has missed one of the items! However, you can work around this easily enough by locking onto the queue’s sync root object when it wakes up and dequeue as many item as there are on the queue. This might not always be applicable to your requirement though.

A much better choice would be to use the Monitor class instead.

Using Monitor.Pulse and Monitor.PulseAll

As Jon Skeet pointed out in his Threading article (see reference) the Auto/ManualResetEvent and Mutex classes are significantly slower than Monitor.

Using the Monitor.Wait, Monitor.Pulse and Monitor.PulseAll methods, you can allow multiple threads to communicate with each other similar to the way the reset events work but only safer. I have found quite a number of different implementations of the Producer-Consumer pattern using these two methods, see the references section for details.

Whilst the implementations might differ and depending on the situation sometimes you might want multi-producer/consumer support and other times you might want to ensure there can only be one producer/consumer. Whatever your requirement might be, the general idea is that both producer(s) and consumer(s) have to acquire a lock on the same sync object before they can add or remove items from the queue. And depending on who’s holding the lock:

  • producer(s) would acquire a lock, add item to the queue, and then pulse, which gives up the lock and wait up other waiting threads (the consumers)
  • consumer(s) would acquire a lock, start listening for items in a continuous loop and wait for a pulse, which gives up the lock (allowing other producers/consumers to get in and acquire the lock). When the consumer is woken up it reacquires the lock and can then safely process new items from the queue.

There are a number of other considerations you should take into account, such as the exit conditions of the consumer’s continuous loop, etc. Have a look at the different implementations I have included in the reference section to get a feel of what you need to do to implement the Producer-Consumer pattern to suit your needs.

Parting thoughts..

Another thing which you should be aware of when implementing any sort of Producer-Consumer model is the need to make the queue thread-safe seeing as multiple threads can be reading/writing to it concurrently. As you might know already, there is a Queue.Synchronized method which you can use to get a synchronized (in other words, thread-safe) version of the queue object.

But as discussed on the BCL Team Blog (see reference), the synchronized wrapper pattern gave developers a false sense of security and led some Microsoft developers to write unsafe code like this:

if (syncQueue.Count > 0) {
    Object obj = null;
    try {
        // count could be changed by this point, hence invalidating the if check
        bj = syncQueue.Dequeue();
    catch (Exception) { } // this swallows any indication we have a race condition
    // use obj here, dealing with null.

Which is why they decided it’s better to force developers to use explicit lock statement around the whole operation.

Another way to think about the problem is to picture the Queue.Synchronized method as the equivalent of a volatile modifier for a reference type which guarantees the latest value of the instance (as opposed to the reference pointer only). Which means it’s save to use in atomic operations (a single instruction) but does not stop interleaving instructions from multiple threads between operations.


MSDN article on how to synchronize a producer and a consumer thread

Jon Skeet’s article on WaitHandles

Jon Skeet’s article on Deadlocks and an implementation of the Producer-Consumer pattern using Monitor

Mike Kempf’s implementation of the Producer-Consumer pattern using Monitor

BCL Team Blog post on why there is not Queue<T>.Synchronized

StackOverflow question on why there’s no Queue<T>.Synchronized