Use a user-defined action to implement automatic tablespace management

Moving older data to a different tablespace can help you save on storage costs. TimescaleDB supports automatic tablespace management by providing the move_chunk function to move chunks between tablespaces. To schedule the moves automatically, you can write a user-defined action.

Using a user-defined action to implement automatic chunk moving

  1. Create a procedure that moves chunks to a different tablespace if they contain data older than the lag parameter.

    1. CREATE OR REPLACE PROCEDURE move_chunks (job_id int, config jsonb)
    2. LANGUAGE PLPGSQL
    3. AS $$
    4. DECLARE
    5. ht REGCLASS;
    6. lag interval;
    7. destination name;
    8. chunk REGCLASS;
    9. BEGIN
    10. SELECT jsonb_object_field_text (config, 'hypertable')::regclass INTO STRICT ht;
    11. SELECT jsonb_object_field_text (config, 'lag')::interval INTO STRICT lag;
    12. SELECT jsonb_object_field_text (config, 'tablespace') INTO STRICT destination;
    13. IF ht IS NULL OR lag IS NULL OR destination IS NULL THEN
    14. RAISE EXCEPTION 'Config must have hypertable, lag and destination';
    15. END IF;
    16. FOR chunk IN
    17. SELECT show.oid
    18. FROM show_chunks(ht, older_than => lag)
    19. SHOW (oid)
    20. INNER JOIN pg_class pgc ON pgc.oid = show.oid
    21. INNER JOIN pg_tablespace pgts ON pgts.oid = pgc.reltablespace
    22. WHERE pgts.spcname != destination
    23. LOOP
    24. RAISE NOTICE 'Moving chunk: %', chunk::text;
    25. EXECUTE format('ALTER TABLE %s SET TABLESPACE %I;', chunk, destination);
    26. END LOOP;
    27. END
    28. $$;
  2. Register the job to run daily. In the config, set hypertable to metrics to implement automatic chunk moves on the metrics hypertable. Set lag to 12 months to move chunks containing data older than 12 months. Set tablespace to the destination tablespace.

    1. SELECT add_job(
    2. 'move_chunks',
    3. '1d',
    4. config => '{"hypertable":"metrics","lag":"12 month","tablespace":"old_chunks"}'
    5. );
note

This procedure uses PostgreSQL’s regular ALTER TABLE ... SET TABLESPACE syntax to move chunks. You could also write the procedure using TimescaleDB’s move_chunk function. The move_chunk function reorders the data as part of the move, which makes subsequent queries faster. It also requires lower lock levels, so the chunk remains available for reads during the move.