[Django]-Django/Python – Updating the database every second

2👍

One of the possible solutions would be to use separate daemonized lightweight python script to perform all the in-game business logic and left django be just the frontend to your game. To bind them together you might pick any of high-performance asynchronous messaging library like ZeroMQ (for instance to pass player’s actions to that script). This stack would also have a benefit of a frontend being separated and completely agnostic of a backend implementation.

1👍

Generally a better solution would be to not update everyone’s currency every second. Instead, store the timestamp of the user’s most recent transaction, their income rate, and their latest balance. With these three pieces of data, you can calculate their current balance whenever needed.

When the user makes a purchase for example, do the math to calculate what their new balance is. Some pseudocode:

def current_balance(user):
    return user.latest_balance + user.income * (now() - user.last_timestamp)

def purchase(user, price):
    if price > current_balance(user):
        print("You don't have enough cash.")
        return

    user.balance = current_balance(user) - price
    user.last_timestamp = now()
    user.save()
    print("You just bought a thing!")

With a system like this, your database will only get updated upon user interaction, which will make your system scale oodles better.

Leave a comment