Search code examples
pythondjangomicroservices

Is using UUId as pk a good idea in microservices?


I am working on a microservice project which contains 4 services developed in django i use dj rest auth to handle login and register process , each service has its own database and the information of users are kept in account service and other 3 services get the users information via an api request to account service , in each service i have only access to logged in user pk (dj rest auth handles this) and when i need to save a record for example location of logged in user ,i save a user object which only has pk alongside other info so the record in db will be like this :

user=request.user(which saves logged in user but i only see the pk)
lat = latitue number
lng = longitude number

everything is fine but if i loose the database of account service and restore the backup and some how the records generate a different pk (for example before restoring backup some new records would be added) from the ones saved in other services which makes a huge problem in all services. the solution i tried is to change the pk to uuid filed but is it a good idea? or maybe it is better to add a uuid filed to user model in account database and in other services i saves this uuid alongside the user's pk ?


Solution

  • The answers to this question may be subjective to different perspectives. Here is my view on this:

    There should be an id field of type INT which is a primary key that can auto-increment. Alongside that, you can add a UUID field, let's say uid.

    Advantages:

    1. Using id as a primary key makes your schema consistent with the rest of the database tables.
    2. You can use the id field as a foreign key and this will take up less space than UUID.
    3. In the public URLs you can use uid field and this does not expose guessable information. For eg, if you use and id, and in URL the resource id is 5, then the attacker can guess that there might be a resource with an id 6, 7. But using uid field which is UUID field, you are not exposing information related to the database.