DEV Community

Admin Fast Value
Admin Fast Value

Posted on

Designing Reliable Payment Tracking for SaaS Applications That Support Partial Payments

When building a SaaS application that handles invoices and payments, one of the easiest mistakes is treating an invoice as a single payment transaction.

In reality, customers frequently pay invoices in multiple installments. They might pay an advance, settle part of the outstanding balance later, and complete the remaining amount after a deliverable is approved.

This introduces several interesting engineering challenges:

  • How do you maintain an accurate outstanding balance?
  • How should partial payments be recorded?
  • How do you prevent duplicate transactions?
  • How should taxes and payment fees be accounted for?
  • What happens when a payment gateway sends the same webhook multiple times?

These are not merely accounting questions. They are database consistency and application architecture problems.

Let's look at how to design a reliable payment tracking system for a SaaS application.

1. Separate invoices from payments

The first architectural decision should be to treat invoices and payments as separate entities.

An invoice represents an amount owed by a customer. A payment represents money actually received.

They have different lifecycles.

For example, consider an invoice with the following details:

Description Amount
Service amount ₹20,000
GST (18%) ₹3,600
Total invoice ₹23,600

The customer doesn't necessarily need to pay the entire amount immediately.

They might pay:

  • First payment: ₹10,000
  • Second payment: ₹8,000
  • Final payment: ₹5,600

The invoice should remain partially paid until the total successful payments equal the invoice amount.

A suitable relational structure is:

Invoices

Field Purpose
id Unique invoice identifier
customer_id Customer reference
invoice_number Human-readable invoice number
subtotal Amount before tax
tax_amount Applicable tax
total_amount Total payable
currency Invoice currency
status Draft, issued, partially paid, paid, etc.
created_at Creation timestamp

Payments

Field Purpose
id Unique payment identifier
invoice_id Associated invoice
transaction_id Gateway transaction reference
amount Actual payment amount
currency Payment currency
status Pending, successful, failed, refunded
payment_method Payment method
received_at Successful payment timestamp

The relationship should be one invoice to many payments.

This design makes it possible to track multiple transactions against a single invoice without modifying the original invoice amount.

2. Calculate outstanding balances using successful payments

One common mistake is updating the invoice's outstanding balance using payment attempts rather than successful payments.

Only successfully received payments should reduce the outstanding amount.

The calculation is straightforward:

const totalPaid = payments
  .filter(payment => payment.status === "successful")
  .reduce((sum, payment) => sum + payment.amount, 0);

const outstanding = invoice.totalAmount - totalPaid;
Enter fullscreen mode Exit fullscreen mode

For financial applications, use integer amounts in the smallest currency unit (paise for INR) or an appropriate decimal representation. Avoid JavaScript floating-point arithmetic for financial calculations.

For example:

Transaction Amount Status
Payment 1 ₹10,000 Successful
Payment 2 ₹8,000 Successful
Payment 3 ₹5,600 Pending

The calculation should be:

  • Invoice total: ₹23,600
  • Successfully received: ₹18,000
  • Outstanding: ₹5,600

The pending payment must not reduce the outstanding balance.

3. Handle payment gateway webhooks carefully

Payment gateways typically communicate payment status changes through webhooks.

A successful checkout redirect does not necessarily mean that money has been received.

For example:

  1. A customer initiates payment.
  2. The gateway processes the transaction.
  3. The customer is redirected to the application.
  4. The application receives a payment confirmation webhook.

The backend should validate the webhook signature and verify the transaction according to the gateway's documented process.

Do not rely exclusively on frontend success-page navigation.

A simplified Express implementation might look like this:

app.post("/webhooks/payment", async (req, res) => {
  const event = req.body;

  // Verify the gateway signature before processing.
  const verified = verifyGatewaySignature(req);

  if (!verified) {
    return res.status(401).send("Invalid signature");
  }

  if (event.status === "successful") {
    await recordSuccessfulPayment(event);
  }

  return res.status(200).send("Received");
});
Enter fullscreen mode Exit fullscreen mode

The signature verification and event parsing must follow the specific payment gateway's documentation.

The important principle is that the backend, not the browser, determines whether a payment is successful.

4. Prevent duplicate payments using idempotency

This is particularly important.

Payment gateways may retry webhook notifications if they do not receive an acknowledgement.

The same successful transaction could therefore reach your application more than once.

Without appropriate protection, you might accidentally record the same payment twice.

Use the gateway transaction ID as an idempotency reference.

For example, create a unique database constraint:

CREATE UNIQUE INDEX
  unique_payment_transaction
ON payments(transaction_id);
Enter fullscreen mode Exit fullscreen mode

Before creating a payment record, check whether that transaction has already been processed.

Ideally, perform the operation within a database transaction.

await db.transaction(async (tx) => {
  const existing = await findPaymentByTransactionId(
    tx,
    gatewayTransactionId
  );

  if (existing) {
    return;
  }

  await createSuccessfulPayment(tx, paymentData);

  await updateInvoiceStatus(tx, invoiceId);
});
Enter fullscreen mode Exit fullscreen mode

The database constraint remains essential because two webhook requests could arrive simultaneously.

Idempotency should be enforced at the database level, not only through application-level checks.

5. Treat payment fees and taxes separately

Another important consideration is distinguishing invoice value from the amount available to the business.

Suppose an invoice contains:

  • Service value: ₹20,000
  • GST: ₹3,600
  • Payment fee: ₹300

The customer pays ₹10,000 initially.

You need to distinguish between:

  1. Amount invoiced.
  2. Amount received from the customer.
  3. Tax liability.
  4. Payment gateway charges.
  5. Net amount available to the business.

Do not assume that all these values are interchangeable.

A useful financial model maintains separate records for invoice items, tax components, payments and transaction fees.

If fees or tax deductions are allocated progressively across installments, the allocation must be deterministic and auditable.

For example, the application should not deduct the entire fee from every installment or deduct the same tax liability twice.

Maintain a clear allocation record for each payment.

6. Maintain an auditable payment history

Financial records should not be treated like ordinary application preferences.

Avoid simply overwriting a payment amount or deleting a transaction when something changes.

Instead, maintain a traceable history of:

  • Payment initiation.
  • Payment confirmation.
  • Failed payment attempts.
  • Refunds.
  • Payment reversals.
  • Invoice adjustments.

A useful approach is to keep the original transaction record and record subsequent financial adjustments separately.

This makes reconciliation easier and provides a reliable history when customers raise payment disputes.

7. Design payment status transitions carefully

An invoice and its payments should have independent statuses.

Invoice statuses

  • Draft
  • Issued
  • Partially Paid
  • Paid
  • Overdue
  • Cancelled

Payment statuses

  • Pending
  • Successful
  • Failed
  • Refunded

Do not mark an invoice as paid simply because a payment was initiated.

Likewise, do not mark an invoice as partially paid unless the application has recorded an actual successful payment.

The invoice status should be derived from the verified payment records and any applicable credit notes or adjustments.

8. Don't forget subscription and revenue tracking

For SaaS products, payment tracking has another dimension: subscription lifecycle management.

A subscription may have:

  • An activation date.
  • A billing period.
  • A renewal date.
  • A payment status.
  • A cancellation date.
  • A payment history.

A subscription being active does not necessarily mean that a new payment has been received.

Similarly, a successful payment does not automatically mean that a subscription should be extended by an entire billing period without considering the existing subscription terms.

Keep subscription state and financial transactions separate, with explicit rules governing how successful payments affect subscription entitlements.

This distinction becomes especially important when supporting upgrades, renewals, refunds and partial payments.

9. Final architecture recommendations

For a SaaS application handling invoices and payments, I would recommend the following principles:

  1. Maintain a one-to-many relationship between invoices and payments.
  2. Record every successful payment independently.
  3. Use gateway transaction IDs for idempotency.
  4. Verify payment notifications on the backend.
  5. Use database transactions for financial updates.
  6. Maintain separate tax, fee and payment records.
  7. Never overwrite financial history without an audit trail.
  8. Derive invoice balances from verified payment records.
  9. Separate subscription status from payment status.
  10. Make financial calculations deterministic and testable.

These principles apply to a wide range of SaaS applications, including creator management, agency management, invoicing and subscription platforms.

For example, creator collaboration management systems such as Collabcy need to account for the relationship between brand deals, invoices, deliverables and multiple payments.

The underlying challenge is the same: financial records must accurately represent what was invoiced, what was received and what remains outstanding.

Conclusion

Partial payments are not an edge case that can be addressed with a simple invoice status field.

They should influence the way a SaaS application's database, payment processing, reconciliation and subscription logic are designed.

Separating invoices from payments, validating gateway notifications, enforcing idempotency and maintaining an auditable transaction history provides a much stronger foundation for financial functionality.

Getting these fundamentals right early can prevent significant reconciliation and data-integrity problems as an application grows.

Top comments (0)