How to know that the account balance of a user needs to be updated after paying/sending an invoice? Lets say there is a service in which users can have a few satoshis but are also able to deposite/withdraw satoshis by paying/sending a lightning invoice. Let us assume the service has some data store which tracks the account balance for the user:

What is the best practice architecture to know that the account balance needs to be updated?

I know there is the waitinvoice RPC-call in c-lightning which tracks the label of an invoice (which could be a user id + some other data). Still in a live application the site should update the balance once the invoice was paid. If however the user left the side and pays the invoice it still needs to work so there needs to be some bridge from the lightning node to the data store. 

In withdrawing the situation gets even more critical since withdrawing can take some time and calls can occure concurrently balance needs to be locked or widthdraw calls have to by synchronized (which I guess ist not preferable) 

So what kind of architectures / best practices are you using?
Both lnd and and c-lightning will include the payment request when notifying you of a payment. I personally used it through lightning charge with c-lightning for satoshis.place.

For each invoice generated (aka an "order"), I would keep a record of it in my database, along with the pixels to be drawn. Then when I see a payment coming in I go and fetch the order and process it.



I'll describe a simple architecture, lets break it down in 2 steps: deposits and withdrawals.

Deposit


You're gonna need to maintain your own database of user accounts.
Include fields like: email, password, unique UUID and balance (you can add 2FA and API keys later).
Generate invoices for deposits, attach the UUID of the user that created it.
Increment the balance of the user when you see the payment come in, remember to do validation like checking amounts sent.


Withdrawals


Have users give you invoices, maintain a table of withdrawal requests.
There might be situations where there isn't enough lightning capacity to pay a user. In this case you might want to provide the option to do off-chain withdrawals instead.
Off-chain withdrawals can be batched with other withdrawal requests, depending on usage of your service. I.e. withdrawals go out at the end of the day / week. This would optimize block space usage and lower any potential related fees paid per user.




I think what you are asking for is essentially software to run your own payment processor. Think about Strike and OpenNode but open-source?

I'm really interested in this topic. I really like the idea of stretching the idea of "Swiss Bank" in everyone's pocket to "PayPal / Stripe in everyone's node". I have some code I've been working on bbut it's still closed source, was intending to release it once MVP. If you're interested we could talk more about this during the Lightning Residency!

-- Koala