drift icon indicating copy to clipboard operation
drift copied to clipboard

Opening Multiple Databases in Drift Causes Unnecessary Isolate Memory Overhead

Open asimolmez opened this issue 4 months ago • 2 comments

Describe the bug

When running multiple isolates, each managing its own Drift database, memory usage in the Dart/Flutter heap grows significantly.

Closing the database connection for an isolate (with a 10-second delay) consistently frees up ~40 MB of heap memory per isolate. The chart below shows the drop in usage after each connection is closed.

Memory View Image

Isolates Image

Additional Informations

When all database connections are open and isolates are active

Image

all connections are closed

Image

asimolmez avatar Aug 09 '25 11:08 asimolmez

Thanks for the report! Could you also share how you're opening the databases for completeness? Would you prefer to use single background isolate for all database instances?

simolus3 avatar Aug 10 '25 20:08 simolus3

class ChatDatabase extends _$ChatDatabase {
  ChatDatabase(this.userId) : super(_openConnection(userId));

  final String userId;

  @override
  int get schemaVersion => 2;

  static QueryExecutor _openConnection(String pubkey) {
    return driftDatabase(name: 'conversation_database_$pubkey');
  }

@simolus3 I created it this way. I investigated, and I believe it’s not related to drift. It’s an expected behavior of the spawning isolate by Dart code.

https://github.com/flutter/flutter/wiki/Flutter-engine-operation-in-AOT-Mode/cf25b22544e2353d3f347e6e04758fa3ad162d59 Isolates launched by Dart code (e.g., Isolate.spawn) inherit the snapshots of their parents.

Additionally, all connections are open because I use watch for certain tables on each database. Do you recommend that we use a single background isolate for multiple databases?

asimolmez avatar Aug 11 '25 09:08 asimolmez