Categories: MongoDB, NoSQL, Performance Posted by nurih on 5/19/2014 4:00 PM | Comments (0)

What's the first thing you hear about NoSQL databases? That they lose your data? That there's no transactions? No joins? No hope for "real" applications?

Well, you *should* be wondering whether a certain of database is the right one for your job. But if you do so, you should be wondering that about "traditional" databases as well!

In the spirit of exploration let's take a look at a common challenge:

You are a bank.

You have customers with accounts.

Customer A wants to pay B.

You want to allow that only if A can cover the amount being transferred.

Let's looks at the problem without any context of any database engine in mind. What would you do? How would you ensure that the amount transfer is done "properly"? Would you prevent a "transaction" from taking place unless A can cover the amount?

There are several options:

  1. Prevent any change to A's account while the transfer is taking place. That boils down to locking.
  2. Apply the change, and allow A's balance to go below zero. Charge person A some interest on the negative balance. Not friendly, but certainly a choice.
  3. Don't do either.

Options 1 and 2 are difficult to attain in the NoSQL world. Mongo won't save you headaches here either.

Option 3 looks a bit harsh. But here's where this can go: ledger. See, and account doesn't need to be represented by a single row in a table of all accounts with only the current balance on it. More often than not, accounting systems use ledgers. And entries in ledgers - as it turns out – don't actually get updated. Once a ledger entry is written, it is not removed or altered. A transaction is represented by an entry in the ledger stating and amount withdrawn from A's account and an entry in the ledger stating an addition of said amount to B's account. For sake of space-saving, that entry in the ledger can happen using one entry. Think {Timestamp, FromAccountId, ToAccountId, Amount}.

The implication of the original question – "how do you enforce non-negative balance rule" then boils down to:

  1. Insert entry in ledger
  2. Run validation of recent entries
  3. Insert reverse entry to roll back transaction if validation failed.

What is validation? Sum up the transactions that A's account has (all deposits and debits), and ensure the balance is positive. For sake of efficiency, one can roll up transactions and "close the book" on transactions with a pseudo entry stating balance as of midnight or something. This lets you avoid doing math on the fly on too many transactions. You simply run from the latest "approved balance" marker to date. But that's an optimization, and premature optimizations are the root of (some? most?) evil..

Back to some nagging questions though: "But mongo is only eventually consistent!" Well, yes, kind of. It's not actually true that Mongo has not transactions. It would be more descriptive to say that Mongo's transaction scope is a single document in a single collection.

A write to a Mongo document happens completely or not at all. So although it is true that you can't update more than one documents "at the same time" under a "transaction" umbrella as an atomic update, it is NOT true that there' is no isolation. So a competition between two concurrent updates is completely coherent and the writes will be serialized. They will not scribble on the same document at the same time. In our case - in choosing a ledger approach - we're not even trying to "update" a document, we're simply adding a document to a collection. So there goes the "no transaction" issue.

Now let's turn our attention to consistency. What you should know about mongo is that at any given moment, only on member of a replica set is writable. This means that the writable instance in a set of replicated instances always has "the truth". There could be a replication lag such that a reader going to one of the replicas still sees "old" state of a collection or document. But in our ledger case, things fall nicely into place: Run your validation against the writable instance. It is guaranteed to have a ledger either with (after) or without (before) the ledger entry got written. No funky states. Again, the ledger writing *adds* a document, so there's no inconsistent document state to be had either way.

Next, we might worry about data loss. Here, mongo offers several write-concerns. Write-concern in Mongo is a mode that marshals how uptight you want the db engine to be about actually persisting a document write to disk before it reports to the application that it is "done". The most volatile, is to say you don't care. In that case, mongo would just accept your write command and say back "thanks" with no guarantee of persistence. If the server loses power at the wrong moment, it may have said "ok" but actually no written the data to disk. That's kind of bad. Don't do that with data you care about. It may be good for votes on a pole regarding how cute a furry animal is, but not so good for business.

There are several other write-concerns varying from flushing the write to the disk of the writable instance, flushing to disk on several members of the replica set, a majority of the replica set or all of the members of a replica set. The former choice is the quickest, as no network coordination is required besides the main writable instance. The others impose extra network and time cost. Depending on your tolerance for latency and read-lag, you will face a choice of what works for you.

It's really important to understand that no data loss occurs once a document is flushed to an instance. The record is on disk at that point. From that point on, backup strategies and disaster recovery are your worry, not loss of power to the writable machine. This scenario is not different from a relational database at that point.

Where does this leave us? Oh, yes. Eventual consistency. By now, we ensured that the "source of truth" instance has the correct data, persisted and coherent. But because of lag, the app may have gone to the writable instance, performed the update and then gone to a replica and looked at the ledger there before the transaction replicated. Here are 2 options to deal with this.

Similar to write concerns, mongo support read preferences. An app may choose to read only from the writable instance. This is not an awesome choice to make for every ready, because it just burdens the one instance, and doesn't make use of the other read-only servers. But this choice can be made on a query by query basis. So for the app that our person A is using, we can have person A issue the transfer command to B, and then if that same app is going to immediately as "are we there yet?" we'll query that same writable instance. But B and anyone else in the world can just chill and read from the read-only instance. They have no basis to expect that the ledger has just been written to. So as far as they know, the transaction hasn't happened until they see it appear later. We can further relax the demand by creating application UI that reacts to a write command with "thank you, we will post it shortly" instead of "thank you, we just did everything and here's the new balance". This is a very powerful thing. UI design for highly scalable systems can't insist that the all databases be locked just to paint an "all done" on screen. People understand. They were trained by many online businesses already that your placing of an order does not mean that your product is already outside your door waiting (yes, I know, large retailers are working on it... but were' not there yet).

The second thing we can do, is add some artificial delay to a transaction's visibility on the ledger. The way that works is simply adding some logic such that the query against the ledger never nets a transaction for customers newer than say 15 minutes and who's validation flag is not set.

This buys us time 2 ways:

  1. Replication can catch up to all instances by then, and validation rules can run and determine if this transaction should be "negated" with a compensating transaction.
  2. In case we do need to "roll back" the transaction, the backend system can place the timestamp of the compensating transaction at the exact same time or 1ms after the original one. Effectively, once A or B visits their ledger, both transactions would be visible and the overall balance "as of now" would reflect no change.  The 2 transactions (attempted/ reverted) would be visible , since we do actually account for the attempt.

Hold on a second. There's a hole in the story: what if several transfers from A to some accounts are registered, and 2 independent validators attempt to compute the balance concurrently? Is there a chance that both would conclude non-sufficient-funds even though rolling back transaction 100 would free up enough for transaction 117 (some random later transaction)? Yes. there is that chance. But the integrity of the business rule is not compromised, since the prime rule is don't dispense money you don't have. To minimize or eliminate this scenario, we can also assign a single validation process per origin account. This may seem non-scalable, but it can easily be done as a "sharded" distributrion. Say we have 11 validation threads (or processing nodes etc.). We divide the account number space such that each validator is exclusively responsible for a certain range of account numbers. Sounds cunningly similar to Mongo's sharding strategy, doesn't it? Each validator then works in isolation. More capacity needed? Chop the account space into more chunks.

So where  are we now with the nagging questions?

  • "No joins": Huh? What are those for?
  • "No transactions": You mean no cross-collection and no cross-document transactions? Granted - but don't always need them either.
  • "No hope for real applications": well...

There are more issues and edge cases to slog through, I'm sure. But hopefully this gives you some ideas of how to solve common problems without distributed locking and relational databases. But then again, you can choose relational databases if they suit your problem.



public ActionResult DoSomething(Foo value)
if (ModelState.IsValid)
return View();

...// do actual work
return View("AllGoodThanks");




public class ValidateModelAttribute : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext filterContext)
if (filterContext.Controller.ViewData.ModelState.IsValid)

filterContext.Result = new ViewResult
ViewName = filterContext.ActionDescriptor.ActionName,
ViewData = filterContext.Controller.ViewData,
TempData = filterContext.Controller.TempData




public ActionResult DoSomething(Foo value)
...// do actual work
return View("AllGoodThanks");














  2. Issue a command to mongod via a client connection


killall -SIGUSR1 mongod







### log rotate

### compress newly rotated

7za a "$f.z" "$f"
rm -f "$f"

### remove files older than x days




Happy admin!




  1. Go to the new portal

Steps 6-8 described here:





My game plan shaped up to :



string GetUserName(string id);
DateTime GetUserBirthdate(string id);


[DataContract(Namespace = "...")]
public class ServiceResponse
    public string Error { get; set; }
    public ResponseStatus Status { get; set; }

Where the status is an enumeration:

[DataContract(Namespace = "...")]
public enum ResponseStatus
    None = 0,
    /// <summary>
    /// Operation completed without failure
    /// </summary>
    Success = 1,
    /// <summary>
    /// General failure
    /// </summary>
    Failure = 2,
    /// <summary>
    /// Client request not valid or not acceptable
    /// </summary>
    ClientFault = 4,
    /// <summary>
    /// Server failed processing request
    /// </summary>
    ServerFault = 8,
    /// <summary>
    /// </summary>
    BackendFault = 16,
    /// <summary>
    /// Convenience value for client fault failure comparison
    /// </summary>
    ClientFailure = Failure + ClientFault,
    /// <summary>
    /// Convenience value for server fault failure comparison
    /// </summary>
    ServerFailure = Failure + ServerFault,
    /// <summary>
    /// Convenience value for backend failure comparison.
    /// </summary>
    BackendFailure = Failure + BackendFault



public class GetUserResponse: ServiceResponse
    string Name{get;set;}
    DateTime Birthdate {get;set;}
    // whatever else a user profile has..
// then the operation signature becomes
public interface IMyService
    GetuserResponse GetUser(string id);
    // and other operations



public class FailFastOperationAttribute : Attribute, IOperationBehavior
    public void Validate(OperationDescription operationDescription) { }
    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        var returnType = operationDescription.SyncMethod.ReturnType;
        dispatchOperation.Invoker = new FailFastOperationInvoker(dispatchOperation.Invoker,returnType);
    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { }
    public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { }


public class FailFastOperationInvoker : IOperationInvoker
    private readonly IOperationInvoker _operationInvoker;
    private readonly Type _returnType;
    public FailFastOperationInvoker(IOperationInvoker operationInvoker, Type returnType)
        _operationInvoker = operationInvoker;
        _returnType = returnType;
    #region IOperationInvoker Members
    public object[] AllocateInputs()
        return _operationInvoker.AllocateInputs();
        object result;
        if (Config.ShouldFailFast())
            outputs = new object[0];
            result = Activator.CreateInstance(_returnType);
            // mark the response as fail fast failure
            result = _operationInvoker.Invoke(instance, inputs, out outputs);
        return result;
        return _operationInvoker.InvokeBegin(instance, inputs, callback, state);
        return _operationInvoker.InvokeEnd(instance, out outputs, result);
    public bool IsSynchronous
        get { return _operationInvoker.IsSynchronous; }











    instance.Id = id;
    instance.Len = length;
    instance.Type = exifType;
    instance.Value = buffer;
    return instance;







Here is a function that may help you

   1: <script type="text/javascript">
   2:        var postToAction = function (sender) {
   5:             $.ajax({
   6:                 url: document.location.href,
   7:                 type: 'POST',
   8:                 dataType: 'json',
   9:                 data: json,
  11:                 success: function (data) {
  12:                     var replyText = JSON.stringify(data);
  14:                 }
  15:             });
  16:         };
  17:     </script>









   1: public class MyJsonValueProviderFactory : ValueProviderFactory
   2: {
   3:     public override IValueProvider GetValueProvider(ControllerContext controllerContext)
   4:     {
   5:         if (controllerContext == null)
   6:         {
   7:             throw new ArgumentNullException("controllerContext");
   8:         }
  10:         if (!controllerContext.HttpContext.Request.ContentType.StartsWith(
  11:                 "application/json", StringComparison.OrdinalIgnoreCase))
  12:         {
  13:             return null;
  14:         }
  17:         object value = Deserialize(controllerContext.RequestContext.HttpContext.Request.InputStream);
  19:         if (value == null)
  20:         {
  21:             return null;
  22:         }
  26:         PopulateBag(bag, string.Empty, value);
  29:     }
  31:     private static object Deserialize(Stream stream)
  32:     {
  35:         if (string.IsNullOrEmpty(str))
  36:         {
  37:             return null;
  38:         }
  42:         return serializer.DeserializeObject(str);
  43:     }
  46:     {
  48:         if (dictionary != null)
  49:         {
  50:             foreach (var entry in dictionary)
  51:             {
  53:             }
  54:         }
  55:         else
  56:         {
  57:             var list = source as IList;
  58:             if (list != null)
  59:             {
  61:                 {
  63:                 }
  64:             }
  65:             else
  66:             {
  67:                 bag[prefix] = source;
  68:             }
  69:         }
  70:     }
  73:     {
  74:         if (!string.IsNullOrEmpty(prefix))
  75:         {
  77:         }
  78:         return propertyName;
  79:     }
  82:     {
  84:     }
  85: }



   2: if (existing != null)
   3: {
   4:     ValueProviderFactories.Factories.Remove(existing);
   5: }
   6: ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());




Happy coding!



Zoom forward a decade.


Or so she thought.


   1: public static QueryComplete EQ(
   2:     string name,
   3:     BsonValue value
   4: )


   1: public string CreateFooQuery(string value)
   2: {
   4:     return query.ToString();
   5: }









return Json([data);




Back to the core problem though.


1) Create our own custom JsonResult implementation




   1: public class TypedJsonResult : JsonResult
   2: {
   3:     public override void ExecuteResult(ControllerContext context)
   4:     {
   5:         if (context == null)
   6:         {
   7:             throw new ArgumentNullException("context");
   8:         }
  10:         if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet)
  12:         {
  13:             throw new InvalidOperationException("JsonRequest GetNotAllowed");
  14:         }
  16:         var response = context.HttpContext.Response;
  20:         if (ContentEncoding != null)
  21:         {
  22:             response.ContentEncoding = ContentEncoding;
  23:         }
  25:         if (Data != null)
  26:         {
  28:             response.Write(serializer.Serialize(Data));
  29:         }
  30:     }
  31: }



   2: {
   4: }





   3: static BiasedTypeResolver()
   4: {
   6:     var appDomain = AppDomain.CurrentDomain;
   8:     {
  10:         {
  11:             _KnownTypes[type.Name] = type;
  12:         }
  13:     }
  14: }
  16: public override Type ResolveType(string id)
  17: {
  18:     var result = Type.GetType(id);
  20:     {
  21:         return result;
  22:     }
  24: }
  26: public override string ResolveTypeId(Type type)
  27: {
  28:     if (type == null)
  29:     {
  30:         throw new ArgumentNullException("type");
  31:     }
  33:     return type.Name;
  34: }







Happy Coding!