Docs Menu

Compact a Realm - Swift SDKicons/link.png

On this page

  • Overview
  • Compact a Realm
  • Make a Compacted Copy
  • How Compacting Works
  • Best Practices
  • Summary

The size of a Realm Database file is always larger than the total size of the objects stored within it. This architecture enables some of realm's great performance, concurrency, and safety benefits.

See also:

Realm writes new data within unused space tracked inside file. In some situations, unused space may comprise a significant portion of a realm file. If file size grows large enough to negatively impact performance, compact the realm.

Use shouldCompactOnLaunch() (Swift) or shouldCompactOnLaunch (Objective-C) on a realm's configuration object to compact a realm. Specify conditions to execute this method, such as:

  • The size of the file on disk
  • How much free space the file contains
Compacting may not occur

Compacting cannot occur while a realm is being accessed, regardless of any configuration settings.

You can save a compacted (and optionally encrypted) copy of a realm to another file location with the Realm.writeCopy(toFile:encryptionKey:) method. The destination file cannot already exist.


Avoid calling this method within a write transaction. If called within a write transaction, this method copies the absolute latest data. This includes any uncommitted changes you made in the transaction before this method call.

Realm compacting works by:

  1. Reading the entire contents of the realm file
  2. Writing the contents to a new file at a different location
  3. Replacing the original file

If the file contains a lot of data, this can be an expensive operation.

Experiment with conditions to find the right balance of how often to compact a realm file. Because the operation can be expensive, don't compact every time you open a realm. Do compact often enough to prevent the file size from growing too large.

  • Realm Database's architecture enables threading-related benefits, but can result in file size growth.
  • Use compacting to manage file size growth.
  • Define conditions for shouldCompactOnLaunch() to compact a realm.
  • Compacting cannot occur if another process is accessing the realm.
Give Feedback
MongoDB logo
© 2021 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.