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

Killing a particular Tomcat thread

Update: This JSP does not work on a thread that is inside some native code.  On many occasions I had a thread stuck in JNI code and it wont work. Also in some cases thread.stop can cause jvm to hang. According to javadocs " This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked". I have used it only in some rare occasions where I wanted to avoid a system shutdown and in some cases we ended up doing system shutdown as jvm was hung so I had a 70-80% success with it.   -------------------------------------------------------------------------------------------------------------------------- We had an interesting requirement. A tomcat thread that was spawned from an ExecutorService ThreadPool had gone Rogue and was causing lots of disk churning issues. We cant bring down the production server as that would involve downtime. Killing this thread was harmless but how to kill it, t

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 can happe

Preparing for an interview after being employed 11 years at a startup

I would say I didn't prepared a hell lot but  I did 2 hours in night every day and every weekend around 8 hours for 2-3 months. I did 20-30 leetcode medium problems from this list https://leetcode.com/explore/interview/card/top-interview-questions-medium/.  I watched the first 12 videos of Lecture Videos | Introduction to Algorithms | Electrical Engineering and Computer Science | MIT OpenCourseWare I did this course https://www.educative.io/courses/grokking-the-system-design-interview I researched on topics from https://www.educative.io/courses/java-multithreading-for-senior-engineering-interviews and leetcode had around 10 multithreading questions so I did those I watched some 10-20 videos from this channel https://www.youtube.com/channel/UCn1XnDWhsLS5URXTi5wtFTA