firebasefluttergoogle-cloud-firestoregoogle-cloud-functionsdelayed-execution

Flutter Firebase delay function


I am creating an event booking app with Flutter and Firebase Firestore. And sometimes if events are popular there is a possibility that a user buys a ticket and gets no seat because somebody was faster, and because of that I want to create a reservation before the purchase that is applied for 5 minutes and if the user doesn't buy within that time range the ticket reservation will be automatically deleted. Can someone give me a suggestion on how to do that?


Solution

  • It's hard to give an answer without knowing your data structure and the business requirements, so here's one way to do it with few assumption:

    In this scenario, whenever a user enters a session to book a ticket, you should use a transaction to:

    Using a transaction here prevents two users from entering a session for the same ticket, and allow you to do multiple operations while making sure you have the correct data.

    If the user ends up buying the ticket, you can mark it as sold. If the five minutes passes, you can end the user session from the client side and mark the ticket as available.

    You've to determine the process based on the business requirement but this is a rough idea of how it can be implemented.

    If you're unfamiliar with transaction, here's a useful reference and a video that explains it: https://firebase.google.com/docs/firestore/manage-data/transactions

    ===== update based on the comment ===

    You can create a cloud function that triggers whenever the ticket status has changed. In the trigger function, you'll get the SeatDocument where you can check if the status changed to blocked. If so, then you can create a Scheduled function that will run after 5 minutes and check if the status has changed to sold. And if not, then you can update the ticket status back to available.

    In short, you can do a lot with both Triggers and Schedule Functions from Cloud Functions. You can also look into callableFunctions that you can use to start a session and to sell a ticket from the server side of Cloud Functions.