1

My application is running inside AWS lambda and needs to write to postgresql. There is a scenario that two lambdas will write to the same row in the db table. Below is the case:

Lambda1: receive order processing event then update order#1 status to processing

Lambda2: receive order completed event then update order#1 status to completed.

In above scenario, Lambda1 and Lambda2 can happen in any order. how can I make sure the final status of the order#1 is completed not processing?

I can do a query before update, but what happen if the other lambda writes to the table in between?

Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523
  • Postgres does row level locking for writes like that. As long as lambda1 starts its write first, it will be fine. – jordanm Feb 16 '21 at 22:42
  • [Locking a specific row in postgres](https://stackoverflow.com/q/51002790/174777) – John Rotenstein Feb 16 '21 at 23:20
  • The problem in my case is that lambda1 and lambda2 may run in different order – Joey Yi Zhao Feb 16 '21 at 23:22
  • How come lambda2 can run before lambda1? I think this is architecture design issue, not postgresql problem? – Marcin Feb 17 '21 at 00:27
  • yes, this is architecture design issue. I am using event sourcing design and the events come to my lambda can be in any order. So that I need to fix in my lambda. The question is what is the best way to handle this case? – Joey Yi Zhao Feb 17 '21 at 02:13
  • Simple: make sure that lambda2 doesn't start before lambda1 completes. – Laurenz Albe Feb 17 '21 at 08:26
  • If you just want to make sure the order, you can write a simple state machine using aws step functions OR if you can invoke them asynchronously, you can use lamda destinations. – samtoddler Feb 17 '21 at 11:17

0 Answers0