Skip to main content

hierarchical locking using mysql database

We are a cloud file server company and one of the requirements we have is to be able to hierarchically lock the paths i.e. for a particula customer if one user is trying to move a path /shared/marketing/Dallas then no one should be allowed to add/delete files/folders in Dallas and its children, also no one should be able to make any edits to shared or marketing folder.  But users should be able to add files to any sibling hierarchies like /Shared/Engineering/test or /private/kpatel or /Shared/QA.

so the requirement is to have an api where I can do

try {
lockManger.lockPaths("/Shared/source", "/Shared/sbc", "/Shared/
target");
.....
....
Do some long running task (may be 1msec to 10 minutes).
....
...
} finally {
   lockManager.releaseLocks();
}

I evaluated some alternatives so here is the summary :
1) Apache commons has this locking api with class org.apache.commons.transaction.locking.DefaultHierarchicalLockManager
and it has a method called as lockInHierarchy that matches our reuirement 100% but only downside is that it uses inmemory locks and we are moving our servers to HA so this is not a solution.

2) Another alternative is to start a seprate  JVM and run DefaultHierarchicalLockManager inside it and expose apis to lock/unlock paths. I have been badly bitten by SPOFs and this is a SPOF because what if this tomcat goes down then you all your running jvms are in a limbo.

3) Another solution is to use Terracotta distributed locking api but I would have to roll out my own hierarchical locking on top of terracotta distributed locks.

4) Same problem was with hazlecast distributed locks.  Also the ops need to be famaliar with it and who will train ops and what if there are bugs then its a whole new learning curve.

5) Last alternative was to design our own locking api based on top of a mysql database table. From our graphite dashboard I can find that for a particular customer the concurrency is not more than 8-10 request per sec so I think designing a locking based on database will work.  The only issue is when you release the lock how do you notify the other waiting threads in a distributed manner. Now I could have used rabbitmq or something JMS for this but it sounds like an overkill considering most of the time a customer is working on diff paths. So I thought to start with a polling based approach +reverse exponential backoff for now and later introduce JMS if required which I dont think we will require.

So I created these tables

CREATE TABLE path_locks (
    customer_id BIGINT NOT NULL,
    path                   VARCHAR(4000) NOT NULL,
    creation_time         DATETIME NOT NULL,
    thread_id             VARCHAR(64) NOT NULL,
    node_id             VARCHAR(64) NOT NULL,
)ENGINE=innodb;

CREATE TABLE customer_locks (
    customer_id BIGINT NOT NULL,
)ENGINE=innodb;

and the logic was to

1)We delete all locks for that node_id on startup of a node and destroy of a node.
2) A quartz job will delete all expired locks (older than timeoutsec+1min).
3)Now to get a lock for /Shared/kpatel/Software/Releases
  while not lock acquired   
    lock sentinel row in customer_locks table for that customer_id to guard against race conditions between query and acquisition steps.
    Fire this query to detect lock conflicts

    select * from path_lock where threadId !='Thread1' and (creation_time-systime) < lockTimeout
          and (path like '/Shared/kpatel/Software/Releases/%' or path in ('/Shared','/Shared/kpatel','/Shared/kpatel/Software', '/Shared/kpatel/Software/Releases'))
   
        If you dont find any conflict then
            Insert the lock row
            Release sentinel lock.
        If you get any conflicts then
            check if you timedout waiting for lock then throw LockTimeoutException?.
            Else
            release sentinel lock
            wait for max(10, 1024/(retryCount%15))msec (reverse exponential backoff to reduce thread starvation). retryCount%15 is done to backoff and not pound the db continously as possibly this is some dead node issue or some long running lock hogger is doing its job and we have to wait.


The real thik in this solution is this reverse exponential backoff where if 10 threads come to acquire locks then we would not bombard the table or we would not starve the threads also as the thread that came first would be more aggresively querying than the thread that came late

This is going to be live soon and I am confident that this should be able to handle the load.

Comments

Popular posts from this blog

Haproxy and tomcat JSESSIONID

One of the biggest problems I have been trying to solve at our startup is to put our tomcat nodes in HA mode. Right now if a customer comes, he lands on to a node and remains there forever. This has two major issues: 1) We have to overprovision each node with ability to handle worse case capacity. 2) If two or three high profile customers lands on to same node then we need to move them manually. 3) We need to cut over new nodes and we already have over 100+ nodes.  Its a pain managing these nodes and I waste lot of my time in chasing node specific issues. I loath when I know I have to chase this env issue. I really hate human intervention as if it were up to me I would just automate thing and just enjoy the fruits of automation and spend quality time on major issues rather than mundane task,call me lazy but thats a good quality. So Finally now I am at a stage where I can put nodes behing HAProxy in QA env. today we were testing the HA config and first problem I immediat...

Adding Jitter to cache layer

Thundering herd is an issue common to webapp that rely on heavy caching where if lots of items expire at the same time due to a server restart or temporal event, then suddenly lots of calls will go to database at same time. This can even bring down the database in extreme cases. I wont go into much detail but the app need to do two things solve this issue. 1) Add consistent hashing to cache layer : This way when a memcache server is added/removed from the pool, entire cache is not invalidated.  We use memcahe from both python and Java layer and I still have to find a consistent caching solution that is portable across both languages. hash_ring and spymemcached both use different points for server so need to read/test more. 2) Add a jitter to cache or randomise the expiry time: We expire long term cache  records every 8 hours after that key was added and short term cache expiry is 2 hours. As our customers usually comes to work in morning and access the cloud file server it ...

Spring 3.2 quartz 2.1 Jobs added with no trigger must be durable.

I am trying to enable HA on nodes and in that process I found that in a two test node setup a job that has a frequency of 10 sec was running into deadlock. So I tried upgrading from Quartz 1.8 to 2.1 by following the migration guide but I ran into an exception that says "Jobs added with no trigger must be durable.". After looking into spring and Quartz code I figured out that now Quartz is more strict and earlier the scheduler.addJob had a replace parameter which if passed to true would skip the durable check, in latest quartz this is fixed but spring hasnt caught up to this. So what do you do, well I jsut inherited the factory and set durability to true and use that public class DurableJobDetailFactoryBean extends JobDetailFactoryBean {     public DurableJobDetailFactoryBean() {         setDurability(true);     } } and used this instead of JobDetailFactoryBean in the spring bean definition     <bean i...