Skip to content

Instantly share code, notes, and snippets.

@anthowen
Forked from dustinrouillard/snowflake.sql
Last active January 18, 2021 09:49
Show Gist options
  • Save anthowen/9dab0b29c6349fb6b2e5b58b611cc99f to your computer and use it in GitHub Desktop.
Save anthowen/9dab0b29c6349fb6b2e5b58b611cc99f to your computer and use it in GitHub Desktop.
DB Best Practices & PostgreSQL Snowflake ID Generator Function
CREATE SEQUENCE IF NOT EXISTS public.global_id_sequence;
CREATE OR REPLACE FUNCTION id_generator(OUT result BIGINT) AS $$
DECLARE
epoch BIGINT := 1610850820000;
seq_id BIGINT;
now_millis BIGINT;
shard_id INT := 1;
BEGIN
SELECT nextval('public.global_id_sequence') % 1024 INTO seq_id;
SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis;
result := (now_millis - epoch) << 23;
result := result | (shard_id << 10);
result := result | (seq_id);
END;
$$ LANGUAGE PLPGSQL;
@anthowen
Copy link
Author

@anthowen
Copy link
Author

best practices for protecting your db before deploying:

  1. back it up
  2. don't expose it to the internet
  3. sanitize/escape inputs
  4. ensure no sequential IDs
  5. Always run up to date version to ensure no vulnerabilities
  6. Limit access
  7. Separate your database server from your app server
  8. If your backing up your db make sure it’s encrypted
  9. make sure to turn synchronization off if you use that in dev!
  10. Automated snapshots.
  11. a strong master password
  12. Create an under priviliged user for the services connecting to it.
  13. Think about a more resilient rollback strategy if you can handle that from a financial point of view (replication factor, main/replicas, bluegreen, etc)
  14. Use SSL certificate to encrypt the connection between your backend and the DB.
  15. Specific user with explicit rights for your data layer connection. i.e. dont just use root
  16. Use soft delete
  17. Have a regular process of testing and certifying said backups work. That way you verify there are good and you know how to quickly recover when something does happen. Rather than figuring it out in a rush then hoping it works. (Experience taught me this, thankfully it worked.)
  18. Test that you're able to restore the DB backup (make sure restore of backups are working. sometimes restore breaks if db versions mismatch)
  19. Change default ports, and use ssl.
  20. Don't run your own server on compute. Use cloud providers like rds or sql from gcloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment