Search code examples
surrealdb

Is there a Time to Live (TTL) feature in SurrealDB?


SurrealDb looks amazing.

It does pretty much everything in one database.

However, I couldn't find one feature I want, which is time to live (TTL) feature that allows automatically expiring data records.

Does SurrealDb already have this feature or is it planned in the future?


Solution

  • Good question!

    This is definitely something we intend to implement and there is an open feature request for TTL too, but in the meantime, you can create a schema like the one below along with a garbage collector or cron job to remove all expired records from the table:

    DEFINE TABLE demo SCHEMAFULL
        PERMISSIONS
            FOR select WHERE ttl < time::now();
    
    DEFINE FIELD some_data ON demo TYPE string;
    DEFINE FIELD ttl ON demo TYPE datetime; 
    

    Note that this will not work for root/ns/db users, as the permission clauses don't count for them. Though, at that point I assume you are connecting via a backend layer, thus controlling the query and thus you would be able to add a filter like WHERE ttl < time::now()

    Hope this helps!