LiteDB icon indicating copy to clipboard operation
LiteDB copied to clipboard

Exception during multiprocess concurrent access to LiteDB

Open podkolzzzin opened this issue 9 years ago • 13 comments

During develop we got such exception:

Exception Information

Message: Timeout. Database is locked for more than 00:01:00 Source: LiteDB TargetSite: Void TryExec(System.Action) HelpLink: Type: LiteDB.LiteException Place: 1 Stack: at LiteDB.FileDiskService.TryExec(Action action) at LiteDB.FileDiskService.DeleteJournal() at LiteDB.TransactionService.Complete(LiteTransaction trans) at LiteDB.LiteTransaction.Commit() at LiteDB.DbEngine.WriteTransaction[T](String colName, Boolean addIfNotExists, Func2 action) at LiteDB.DbEngine.Update(String colName, IEnumerable1 docs) at LiteDB.LiteCollection`1.Update(BsonValue id, T document)

Single litedb file is used across 10 processes. I've read that you completely updated concurrency, is this problem still possible in v3?
If such kind of concurrency isn't task of litedb we probably could use mutex, not concurrent access to db for many processes.

One more question: when stable version of v3 would be available?

Thanks for litedb, it's really simple and fast!

podkolzzzin avatar Dec 06 '16 14:12 podkolzzzin

Hi @podkolzzzin, take a look on this thread: #332

v3 is almost done, just finishing some tests and upgrade database. More few weeks ;)

mbdavid avatar Dec 06 '16 15:12 mbdavid

Hello @mbdavid i have just updated to v3 beta 3 looking forward to this fix, but immediately received exception in multiprocess context.

Exception Information Message: Timeout. Database is locked for more than 00:00:00. Source: LiteDB TargetSite: Void TryExec(System.Action, System.TimeSpan) HelpLink: Type: LiteDB.LiteException Place: 1 Stack: at LiteDB.FileHelper.TryExec(Action action, TimeSpan timeout) at LiteDB.StreamExtensions.TryLock(FileStream stream, Int64 position, Int64 length, TimeSpan timeout) at LiteDB.FileDiskService.d__24.MoveNext() at LiteDB.TransactionService.Recovery() at LiteDB.LiteEngine..ctor(IDiskService disk, String password, Nullable1 timeout, Int32 cacheSize, Logger log) at LiteDB.LiteDatabase.<>c__DisplayClass10_0.<.ctor>b__0() at LiteDB.LazyLoad1.get_Value() at LiteDB.LiteCollection1.<Find>d__17.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at LiteDB.LiteCollection`1.FindById(BsonValue id)

podkolzzzin avatar Jan 10 '17 13:01 podkolzzzin

Hi @podkolzzzin, can you test with current master branch? I found an bug in Find operation and fix in master but not release yet. If problem persist, please, re-open this issue.

mbdavid avatar Jan 10 '17 19:01 mbdavid

Hi @mbdavid I tried with current master branch, it looks like you fixed it. My congratulations. As I understood now LiteDB is ready to work in multiprocess environment. It's really cool, my congratulations! When could we expect v3 stable? It's really important for us, because we are going to have a release this month, and if we do it on v2, we'll have to do something than to update users' database files.

podkolzzzin avatar Jan 11 '17 11:01 podkolzzzin

Hi @podkolzzzin, thanks! My plans is release v3 next weekend in nuget. I need just review some code, do more unit tests and publish, After this, I will update all wiki documentation and site.

mbdavid avatar Jan 11 '17 11:01 mbdavid

I tried one code-sample on your code from 11/01/17 And received the same exception. Launch this code and wait a couple of minutes.

I have written thread sleep because we have quite big amount of information which could be saved inside of the transaction.

using LiteDB;
using System;
using System.Threading;

namespace LiteDbTest
{
    public class Test
    {
        public string Test1 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 100; i++)
            {
                Thread t = new Thread(Proc);
                t.Start();
            }
        }

        public static void Proc()
        {
            try
            {
                using (LiteDatabase db = new LiteDatabase("file1.db"))
                {
                    using (var t = db.BeginTrans())
                    {
                        db.GetCollection<Test>("Test").Insert(new Test()
                        {
                            Test1 = "Test"
                        });
                        Thread.Sleep(10000);
                        t.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Faild");
                throw;
            }
        }
    }
}

podkolzzzin avatar Jan 13 '17 10:01 podkolzzzin

It was time and we had to publish new release very soon. So, we had to fix this ASAP. So I implemented multiprocess ReadWriteLock. I used Mutex, Semaphore and EventWaitHandle inside. If it is acceptable for you I can share my solution.

podkolzzzin avatar Feb 07 '17 08:02 podkolzzzin

Hi @podkolzzzin, I implemented using FileStream.Lock command. Thanks

mbdavid avatar Feb 10 '17 22:02 mbdavid

I downloaded LiteDB source code until commit 1afb0b1b99a53afe6b5785c28cf2666650712853 (latest now) And launched the code I had posted before. There is still an exception

Unhandled Exception:Unhandled Exception:Unhandled Exception: LiteDB.LiteException: Timeout. Database is locked for more than 00:01:00.
   at LiteDB.FileHelper.TryExec(Action action, TimeSpan timeout) in C:\Users\AndreyPod\Saved Games\Downloads\LiteDB-master\LiteDB\Utils\FileHelper.cs:line 72
   at LiteDB.StreamExtensions.TryLock(FileStream stream, Int64 position, Int64 length, TimeSpan timeout) in C:\Users\AndreyPod\Saved Games\Downloads\LiteDB-master\LiteDB\Utils\Extensions\StreamExtensions.cs:line 56
   at LiteDB.FileDiskService.Lock(LockState state, TimeSpan timeout) in C:\Users\AndreyPod\Saved Games\Downloads\LiteDB-master\LiteDB\Engine\Disks\FileDiskService.cs:line 321
   at LiteDB.LockService.LockReserved() in C:\Users\AndreyPod\Saved Games\Downloads\LiteDB-master\LiteDB\Engine\Services\LockService.cs:line 129
   at LiteDB.LockService.Reserved() in C:\Users\AndreyPod\Saved Games\Downloads\LiteDB-master\LiteDB\Engine\Services\LockService.cs:line 66
   at LiteDB.LiteEngine.BeginTrans() in C:\Users\AndreyPod\Saved Games\Downloads\LiteDB-master\LiteDB\Engine\Engine\Transaction.cs:line 19
   at LiteDB.LiteDatabase.BeginTrans() in C:\Users\AndreyPod\Saved Games\Downloads\LiteDB-master\LiteDB\Database\LiteDatabase.cs:line 113
   at LiteDbTest.Program.Proc() in C:\Users\AndreyPod\Documents\Visual Studio 2015\Projects\LiteDBtests\LiteDBtests\Program.cs:line 33
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

podkolzzzin avatar Feb 13 '17 12:02 podkolzzzin

I can confirm that this is still a legitimate issue. When the LiteDB database is used by multiple processes, you have to disable the journal feature, in order for it, not to timeout. Herewith the code that saved my bacon.

    var databaseName = Server.MapPath("~/App_Data/database.db");
    var connectionString = String.Format("filename={0};journal=false", databaseName);
    using (var db = new LiteDatabase(connectionString))
    {
        var col = db.GetCollection<MyCollection>("dbCollectionName");
        var user = new User 
        {
            Firstname = "john"
            Surname = "doe"
        };

         // Insert new user
         col.Insert(user);
    }

chesney avatar Apr 11 '17 05:04 chesney

Hello, I am using version 3.1.0 and I have having the same issue. I have tried @chesney suggestion of disabling the journal feature but the problem is that if I have one or more processes simply trying to Find records, the database is locked for Write. I have also tried setting the connection string variable "Mode" to "ReadOnly" for the instances that are performing the Find and "Shared" for the single instance trying to Write. I have also tried with and without Transactions calls for the write. No matter what I try the write operation eventually times out.

vbguyny avatar Jun 16 '17 04:06 vbguyny

Is there any update regarding a fix for this issue?

vbguyny avatar Apr 22 '18 02:04 vbguyny

Hi @vbguyny, try use v4 version, because concurrency was re-write to work better than v3.

mbdavid avatar Apr 22 '18 20:04 mbdavid