Is there any TTL (Time To Live ) for Documents in Firebase Firestore

Viewed 12365

Is there any TTL option on documents for Firebase Firestore . Where documents get auto deleted after that amount time

3 Answers

Update (2022-07-26): Firestore just added the option to set a time-to-live policy on collection groups. I'm still leaving the custom approach below, as those give you control over the expunge moment which (for now) isn't possible with the built-in feature.


The easiest way to build it yourself is by:

  1. Adding a expirationTimestamp property to your documents.

  2. Denying read of documents whose expiration has passed in your security rules.

     match /collection/{document} {
       allow read: if resource.data.expirationTimestamp > request.time.date();
     }
    

    Unfortunately this means that you won't be able to query the collection anymore. You'll need to access the individual documents.

  3. Periodically run Cloud Functions code to delete expired documents.

Also see Doug's excellent blog post describing this process: How to schedule a Cloud Function to run in the future with Cloud Tasks (to build a Firestore document TTL).

As of July 26th 2022, TTL Policies for Firestore were released as a preview feature (which means its not ready for production).

In order to use TTL Policies in Firestore, make sure that your documents have a field (of type Date & Time) to define the expiration date of that document (let's name the field expireAt for example).

And then follow the steps outlined in the documentation:

  1. Go to the Cloud Firestore Time-to-live page in the Google Cloud Platform Console.
  2. Go to the Time-to-live page.
  3. Click Create Policy.
  4. Enter a collection group name and the timestamp field name (expireAt in our example).
  5. Click Create.
Related