Skip to content

Calculate balances in database #234

Closed
Closed

Description

@FriesischScott

There is an issues where group balances are incorrect after deleting an expense or changing the currency.

In my case, one group member's balance was off exactly his portion of a deleted expense. In another case we updated an expense from EUR to USD and the USD where still shown for some users.

I've verified that the data in ExpenseParticipant was correct in both cases.

Is there a specific reason for tracking expenses and balances separately? As we can see, keeping track of one expense in four tables (Expense, ExpenseParticipant, Balance and GroupBalance) is difficult. All the info is in the ExpenseParticipant table and the balances could be efficiently computed in the database.

For example, this query computes the balance for user 9 in group 3.

select sum("ExpenseParticipant".amount) from "Expense" join "ExpenseParticipant" on id = "expenseId" where "groupId"=3 and "userId"=9 and "deletedAt" is null;

With some additional group by magic all balances for an entire group can be calculate and I'm sure prisma can do the same.

If you're interested I'd be happy to give this a go and prepare a PR.

Activity

  1. krokosik commented on May 29, 2025

    @krokosik
    Collaborator

    I guess the motivation was to save on these calculations. For example, our work group has had a Splitwise group with many people for years with daily expenses added. Performing summation on each app open for all participants, with hundreds of expenses might be too expensive. Now scale it to many groups on a cloud instance, which @KMKoushik maintains.

    Of course I am just guessing what was the motivation, but I do agree that the logic is convoluted and this approach is very error prone. Perhaps running all of it is just as expensive, but maybe that's nothing for a Postgres. Judging by how little SQL functionality is actually used in the app, I guess the author felt more comfortable with writing TS and that led us here.

    Overall I am very open to your approach, but would have to see some PoC, with the logic reduction and I think we also need a green light from @KMKoushik

  2. FriesischScott commented on May 29, 2025

    @FriesischScott
    ContributorAuthor

    Sounds like a good plan. I'll prepare a proof of concept and we'll see where it goes from there.

  3. krokosik commented on May 29, 2025

    @krokosik
    Collaborator

    Fantastic! Thank you

  4. krokosik commented on Jun 2, 2025

    @krokosik
    Collaborator

    If this works out I guess it will make #198 obsolete. My main concern is the performance, I wonder what would be the impact on a locally deployed Postgres database when we have say 30 members with a history of a 10k, 100k, 1M expenses.

  5. added theissue type on Jun 2, 2025
  6. krokosik commented on Jun 8, 2025

    @krokosik
    Collaborator

    @FriesischScott @guenzd I have created a PoC balance SQL query in branch remove-balances. I found Prisma too limiting and decided to go for TypedSQL queries, however I am still worried about performance and will try working on some stress tests. Let me know what you think about my approach and I'd be happy to hear your opinions.

  7. FriesischScott commented on Jun 8, 2025

    @FriesischScott
    ContributorAuthor

    @FriesischScott @guenzd I have created a PoC balance SQL query in branch remove-balances. I found Prisma too limiting and decided to go for TypedSQL queries, however I am still worried about performance and will try working on some stress tests. Let me know what you think about my approach and I'd be happy to hear your opinions.

    I''ve also opted for typedSQL it works great. So far I've implemented group balances for the group overview and member balances for individual groups. You can find it here: https://github.com/FriesischScott/split-pro/tree/sql-balances

  8. FriesischScott commented on Jun 8, 2025

    @FriesischScott
    ContributorAuthor

    I'll open a draft PR with my changes tomorrow for better review.

  9. guenzd commented on Jun 9, 2025

    @guenzd

    Hi, I did not have the time to fully dig in, the SQL itself looks ok of course.

    But here are some general thoughts:

    • Everything serverside should be super lightweight, since we all want cheep apps to run.
    • Databases are very good at storing data / reading data.
    • Eventually one might want some sort of "audittrail", meaning that deleting /updating transactions will be saved internally as new rows.

    We don't we just save the group balance in a separate table (that does not require history). We read only the new transaction together with the previous balance. Its sum must be 0 all the times, which is a good checker. At the end, people should rely on the computations on the app, it is about real money after all.

  10. FriesischScott commented on Jun 9, 2025

    @FriesischScott
    ContributorAuthor
    * Databases are very good at storing data / reading data.
    

    Yes! This is what SQL is made for and it should scale effortlessly with proper indexes

    * Eventually one might want some sort of "audittrail", meaning that deleting /updating transactions will be saved internally as new rows.
    

    I don't think what this app needs is a detailed history of changes made to expenses.

    We don't we just save the group balance in a separate table (that does not require history). We read only the new transaction together with the previous balance. Its sum must be 0 all the times, which is a good checker. At the end, people should rely on the computations on the app, it is about real money after all.

    I'm not exactly sure what you mean here but the whole point of my proposed change is to get rid of the balance tables entirely because keeping them up to date with changes is difficult and introduces unnecessary layers prone to mistakes.

  11. guenzd commented on Jun 9, 2025

    @guenzd

    Afterall, people will compare the functionality with the commercial product. In a group with a larger user base (at work, say), all changes should be at least trackable.

    At the same time, we have a group lasting back 5 years with a lot of users and transactions. Updating the balances / reading the balances in the app should be "quick" and cheap - so not requiring to read all previous transactions back to Noah's arc to recompute the balance.

    Computing them in db is a great idea, but I would save them there as well. I have created some test data generators, will upload them soon so we can see about performance impact.

  12. krokosik commented on Jun 9, 2025

    @krokosik
    Collaborator

    Yeah, performance wise this is probably gonna suck. I was looking into Prisma caching, but it seems to be a paid feature, so maybe we should keep the balances and invalidate them upon adding a new expense? If the stress tests show significant performance impact, we will probably not go forward with this change, this is a PoC attempt.

  13. FriesischScott commented on Jun 10, 2025

    @FriesischScott
    ContributorAuthor

    It doesn't seem like you guys know how efficient SQL databases are. I've added a function to the seed file to create 100k expenses in the group so we can stress test. That should be way beyond what a typical group has. The query to compute the member balances executes in ~80ms.

    The issue was instead that it tries to add all 100k expenses to the list when viewing the group. For now I capped it at 100.

  14. krokosik commented on Jun 10, 2025

    @krokosik
    Collaborator

    My man, I'm aware that they are efficient, that's why I wanted to explore this with you and see the efficiency ourselves. That being said, unfortunately I do not share your enthusiasm. While 100k is a bit extreme, I would not consider almost ~100ms order negligible. Think of all the people self hosting their services on a Raspberry Pi, think of a service, like the cloud hosted SplitPro, having multiple groups going a couple of years. 80 ms alone is A LOT for a single request in web development and the database has only matching records. What if we also have 1M of unrelated expenses? Another issue I see is the group you tested on has 5 participants. On our instance we have a group with 20 members and I can easily imagine more, that's why I recommended testing with 30.

    I'm not saying the result is not good, it's pretty amazing, but it is not enough to convince me that we can go ahead with the current state of affairs.

    Going back to display, yeah an infinite scroll or paging is definitely necessary for the Expense List, but it seems no one has reached this scale yet :)

    To sum up, yes it seems fine, but we should explore more to not have to revert all of this in the future. What @guenzd said also appeals to me and I'm thinking of some hybrid approach, as in we still have a balance table, but we use the SQL query on all expenses to calculate it?

  15. guenzd commented on Jun 10, 2025

    @guenzd

    Hi, we could write a stored procedure (I can demo that) to update expenses on db - this could be even faster than via TS. In general, i would not put too much on 80ms (which is a local/local deployment on a maybe very fast cpu + ssd) but just the pure amount of CPU needed to compute my own balance - if I am in 10 groups at once for instance. To just display the page, the DB should just give back the data (with pagination this is a good idea). In different areas (and dbms) I experimented a lot with views, indexed views and so on, and more often than not an additional table was the better solution.

    On the extreme, one could even use triggers on each change in the Expenses table, but this would make mass import (from csv) super slow.

  16. FriesischScott commented on Jun 10, 2025

    @FriesischScott
    ContributorAuthor

    My man, I'm aware that they are efficient, that's why I wanted to explore this with you and see the efficiency ourselves. That being said, unfortunately I do not share your enthusiasm. While 100k is a bit extreme, I would not consider almost ~100ms order negligible. Think of all the people self hosting their services on a Raspberry Pi, think of a service, like the cloud hosted SplitPro, having multiple groups going a couple of years. 80 ms alone is A LOT for a single request in web development and the database has only matching records. What if we also have 1M of unrelated expenses? Another issue I see is the group you tested on has 5 participants. On our instance we have a group with 20 members and I can easily imagine more, that's why I recommended testing with 30.

    I'm not saying the result is not good, it's pretty amazing, but it is not enough to convince me that we can go ahead with the current state of affairs.

    Going back to display, yeah an infinite scroll or paging is definitely necessary for the Expense List, but it seems no one has reached this scale yet :)

    To sum up, yes it seems fine, but we should explore more to not have to revert all of this in the future. What @guenzd said also appeals to me and I'm thinking of some hybrid approach, as in we still have a balance table, but we use the SQL query on all expenses to calculate it?

    Apologies, I meant no offence.

    I understand of course that we have to be absolutely sure this will work out for everyone.
    I'll update the seed to a larger test case more represantive of the real world.

    However, I think unrelated expenses should impact the speed very little if at all. Can't hurt to check though.

    A hybrid approach could be interesting as well.

  17. FriesischScott commented on Jun 11, 2025

    @FriesischScott
    ContributorAuthor

    What exactly is the use case we're optimizing for here?

    I went for a hundred thousand expenses in a group which with 5 members is 500k rows to sum as a test because I believe no one will or should ever reach that. You mention 30 members in a group. Even with 10.000 expenses and everyone involved in all expenses that is significantly less.

    Most people running this software will selfhost it (as you mentioned) for a group of friends/family/colleagues and the load on each instance should be relatively low. I don't expect too many will use the official instance. Do you have a rough estimate on how many users/ expenses the official instance is running?

    Regardless, I'll still create a test case with more and larger groups.

  18. guenzd commented on Jun 11, 2025

    @guenzd

    Interesting to know - I would not really want to self host to be honest.

  19. krokosik commented on Jun 11, 2025

    @krokosik
    Collaborator

    Apologies, I meant no offence.

    None taken :)
    Sorry, words online tend to come out sideways

    Most people running this software will selfhost it (as you mentioned) for a group of friends/family/colleagues and the load on each instance should be relatively low. I don't expect too many will use the official instance. Do you have a rough estimate on how many users/ expenses the official instance is running?

    You don't know that. I don't know that. While I agree that probably no one will reach a 100k expenses, we do not want to introduce significant overhead for the instances and I would like to keep the app as lightweight as possible. This goes both ways: a self hosted RPi server and a cloud instance priced per CPU usage. The more we dig into it, the more I learn how cool DBs are and I really appreciate the effort you put in. I just lack the conviction that refactoring/fixing the balance update logic is not going to be better :/

  20. FriesischScott commented on Jun 11, 2025

    @FriesischScott
    ContributorAuthor

    Interesting to know - I would not really want to self host to be honest.

    fair enough

  21. krokosik commented on Jun 11, 2025

    @krokosik
    Collaborator

    On the other hand, I agree that the benefits of not having all the balance logic in the code are pretty great and for now, Split Pro is a small project for small use cases. I would go ahead with these changes, but also test the aforementioned scenarios, just to have a good understanding of what PSQL is capable of. Thank you so much for all your work on this, I am now focusing on polishing the 1.4 release and will delve more into this PR next week.

  22. krokosik commented on Jun 11, 2025

    @krokosik
    Collaborator

    @guenzd Yeah, all these more advanced DB features sound really good, but unfortunately they do not seem to be that well supported in Prisma from what I've read. While it is doable with extensions, I feel like we may lose some observability/maintainability this way and it might be best to keep it simple.

  23. guenzd commented on Jun 11, 2025

    @guenzd

    Yes the pros and cons of ORM systems, well aware of this.
    prisma/orm#20865
    It seems doable and one should use a large test data set to compare the 2 approaches.

  24. FriesischScott commented on Jun 12, 2025

    @FriesischScott
    ContributorAuthor

    On the other hand, I agree that the benefits of not having all the balance logic in the code are pretty great and for now, Split Pro is a small project for small use cases. I would go ahead with these changes, but also test the aforementioned scenarios, just to have a good understanding of what PSQL is capable of. Thank you so much for all your work on this, I am now focusing on polishing the 1.4 release and will delve more into this PR next week.

    Good plan 👍. I'll prepare a much better test case with more and larger groups for you until next week.

  25. changed the title [-]Deleting or modifying group expenses updates balances incorrectly[/-] [+]Calculate balances in database[/+] on Jun 28, 2025
  26. added this to the 1.6 milestone on Aug 10, 2025
  27. krokosik commented on Aug 28, 2025

    @krokosik
    Collaborator

    A simple optimization that popped into my mind is setting the settled up date. We could add a timestamp of when the balance where zeroed for the last time and don't fetch expenses before that. Of course upon editing or deleting a past expense we would have to reset this timestamp.

    Another caching pattern that could be more robust is caching the query response itself and similiarly fetch expenses only after that.

  28. removed this from the 1.6 milestone on Sep 2, 2025
  29. added this to the 1.6 milestone on Sep 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions