Search code examples
concurrencyblocking

How to handle money transactions in non-blocking system?


I'm doing an ad server (sort of RTB), there are advertisers who pay to promote their ad campaigns.

When the user watched the ad I want to charge the advertiser.

Ad campaigns should participate in auctions without blocking, means he can bid for multiple ad requests at the same time. It would make it difficult to charge advertiser immediately since I'll have to block his balance.

Another approach is to not charge him immediately, but in the separate process once every N seconds, and hope so he didn't buy more impressions than he can afford. I can make some sort of threshold credit he should have to participate in auctions, it would eliminate most of the overruns but what if the process is exited and the advertiser wasn't charged and overrun a lot, that would be a problem.

Can someone please advise me how these things are usually handled, maybe recommend some book/article on the topic, please?


Solution

  • If this is a problem of asynchronous programming, meaning that you are concerned about overcharging a bidder when they place too many impression bids at once. Then I suggest using a mutex (i.e. locking system). You can set a threshold on the number of locks a bidder can have in your system at any given time. This threshold can be equivalent to the maximum amount the bidder is willing to spend on impressions. When the bidder requests a bid a lock for that bid on his account should be sent to your server. When the server responds with the ok response that the lock has been created, then the bid can take place. The bid is active until the lock is released by your server. This makes it so the server keeps track of all the bids and places locks on all of them. If the bidder has a threshold of 10 bids and he tries to make a bid for the 11th the server will not release a lock to the bidder to make this bid. Furthermore, if you are using a microservice architecture I suggest making a transaction manager service to handle all these requests and even use Saga based transactions for rollback functionally in case of a server failure.

    profile for Dalton at Stack Overflow, Q&A for professional and enthusiast programmers