Portfolio

ItsJiran

Home/Projects/

Sejuta Baitullah — Financial & Referral Platform

Fintech

Sejuta Baitullah — Financial & Referral Platform

ACID-compliant ledger and multi-level referral system securing over IDR 400M++ in transactions, deployed in 7 days with AI-augmented workflows and zero critical bugs after 6 months in production.

Jibril
Jibril Gilang Ramadhan
·2025-10-20

Table of Contents

#Key Achievements

Achievements

  • Performance·Zero critical bugs in production—leveraging AI-augmented workflows to deploy the financial ledger in just 1 week.
  • Impact·Protecting IDR 400M+ volume through real-time validation and audit trails.
  • Result·Accelerated business launch by deploying a stable platform in 1 week, enabling immediate commercial transactions for the company.

#The Beginning

The mandate for Sejuta Baitullah was clear but daunting: the business required a secure, robust financial system to be live in just 7 days. They needed a platform capable of handling commercial transactions immediately without risking data discrepancies. As a Fullstack Engineer, I was tasked with orchestrating this rapid deployment while building a highly complex, multi-level referral and commission system from the ground up.

#Challenges

Building a fintech platform in a week is inherently risky. The biggest challenge wasn't just the tight deadline, but the absolute zero-tolerance for data inconsistencies. I had to develop a complex commission system that could seamlessly split a single transaction payment into multiple wallets—ranging from administrative accounts to individual user savings.

Race conditions and high-frequency wallet updates were a constant threat to the integrity of over IDR 300 million in user funds. On top of the financial complexity, the business needed a way to visualize massive referral trees and easily move referred users across different branches. Standard recursive database queries for a tree this large would quickly bottleneck the application and tank performance.

#What I've Learned

This project taught me the immense value of strategic delegation in modern development—specifically, delegating to AI. By leveraging Claude AI for frontend components and Gemini 2.5 Pro to accelerate general boilerplate coding, I could focus 100% of my cognitive load on the core backend architecture and complex referral algorithms.

I also learned the art of deliberate simplicity. Choosing the seamless integration of Laravel and Inertia.js allowed for rapid iteration cycles. By actively avoiding over-engineering, I maintained system maintainability and met the production deadline ahead of schedule, proving that speed does not have to come at the expense of security or quality.

#Deep Dive of Some Features That I've Built

#ACID Ledger System & Fund Orchestration

To ensure absolute data consistency across all wallet splits, I implemented a strict ACID-compliant Ledger System. Every incoming transaction strictly balances with allocated or outgoing funds.

I engineered a dedicated Service Layer for fund orchestration. To prevent race conditions during high-frequency wallet updates, I utilized lockForUpdate and wrapped all wallet movements in database transactions for atomicity (DB::Transaction). This rigorous approach guaranteed every balance change was auditable and safe.

public function handle(Model $user, Model $paymentSource): Collection
{
    return DB::transaction(function () use ($user, $paymentSource) {
        $data = $this->prepareOrchestrationData($user);

        $this->performValidation(
            $paymentSource,
            $data->amounts,
            $data->totalReferralAmount,
        );

        $adminAccounts = $this->getAdministrationAccounts();
        $allTransactions = new Collection();

        $this->createUserInsurance($user, $data->insuranceProduct);

        $allTransactions->push(
            $this->accountService->credit(
                $adminAccounts->insurance,
                $data->insuranceProduct->amount,
                AccountTransactionPurpose::INSURANCE,
                AccountTransactionStatus::COMPLETED,
                $paymentSource,
                "Pembayaran Asuransi " . $adminAccounts->insurance->name,
            ),
        );

        // ... more wallet splits

        $referralTransactions = $this->createReferralTransactions(
            $data->referralAmountsSettings,
            $data->referralTargets,
            $paymentSource,
        );
        $allTransactions = $allTransactions->merge($referralTransactions);

        return $allTransactions;
    });
}

This code relies on a specialized database design featuring polymorphic relations on account_transactions. This acts as the immutable ledger, making the system highly auditable and scalable for future features.

Rendering diagram...

#High-Performance Referral Tree (Closure Table)

To solve the performance bottleneck of querying massive referral downlines, I abandoned traditional recursive parent_referral_code traversal (which runs at O(n²) time complexity) and implemented a Closure Table pattern. This reduced tree querying to O(1) via a single indexed JOIN.

Rendering diagram...

With this schema, querying the referral tree is incredibly fast:

// Query specific depth downline
$descendants = ReferralPath::where("ancestor_id", $startUser->id)
    ->where("depth", $targetDepth)
    ->get();

// Query all downlines in a range
$descendants = ReferralPath::where("ancestor_id", $startUser->id)
    ->where("depth", ">=", $minDepth)
    ->get();

The most complex hurdle was enabling a user to move to a different branch without tearing down and rebuilding the entire database table. I engineered an algorithm that reattaches existing closure rows to the new parent's ancestor chain, generates new rows only where extra depth is needed, and prunes orphaned rows from the old chain:

public function updateUserReferralPaths(User $user, string $oldParentReferralCode, string $newParentReferralCode): void
{
    $currentDescendant = ReferralPath::where("ancestor_id", $user->id)
        ->whereNot('depth', 0)
        ->pluck('descendant_id')
        ->toArray();

    $old_parent = User::where('referral_code', $oldParentReferralCode)->first();
    $new_parent = User::where('referral_code', $newParentReferralCode)->first();

    $old_parents_tree = $old_parent->getUpperlines()->toArray();
    $new_parents_tree = $new_parent->getUpperlines()->toArray();

    $depths_old_parents = count(array_count_values(array_keys($old_parents_tree)));
    $depths_new_parents = count(array_count_values(array_keys($new_parents_tree)));

    $relative_depths = 0;

    // Reattach shared depth levels from old chain to new chain
    while ($depths_new_parents > 0 && $depths_old_parents > 0) {
        $new_anc = $new_parents_tree[array_key_last($new_parents_tree) - ($depths_new_parents - 1)];
        $old_anc = $old_parents_tree[array_key_last($old_parents_tree) - ($depths_old_parents - 1)];

        ReferralPath::where('ancestor_id', $new_anc['id'])
            ->where('descendant_id', $user->id)
            ->delete();

        ReferralPath::where('ancestor_id', $old_anc['id'])
            ->where('descendant_id', $user->id)
            ->whereNot('depth', 0)
            ->update(['ancestor_id' => $new_anc['id'], 'descendant_parent_id' => $new_parent->id]);

        if (!empty($currentDescendant)) {
            ReferralPath::where('ancestor_id', $new_anc['id'])
                ->whereIn('descendant_id', $currentDescendant)
                ->delete();
        }

        ReferralPath::where('ancestor_id', $old_anc['id'])
            ->whereIn('descendant_id', $currentDescendant)
            ->update(['ancestor_id' => $new_anc['id']]);

        $relative_depths++;
        $depths_new_parents--;
        $depths_old_parents--;
    }

    // Generate new rows for extra depth on new parent side
    if ($depths_new_parents > 0) {
        $relative_depths++;
        while ($depths_new_parents > 0) {
            $new_anc = $new_parents_tree[array_key_last($new_parents_tree) - ($depths_new_parents - 1)];

            ReferralPath::where('ancestor_id', $new_anc['id'])
                ->where('descendant_id', $user->id)
                ->delete();

            ReferralPath::create([
                "ancestor_id"          => $new_anc['id'],
                "descendant_id"        => $user->id,
                "descendant_parent_id" => $new_parent->id,
                "depth"                => $relative_depths,
            ]);

            DB::table('referral_paths')
                ->where('ancestor_id', $new_anc['id'])
                ->whereIn('descendant_id', function ($q) use ($user) {
                    $q->select('descendant_id')
                      ->from('referral_paths')
                      ->where('ancestor_id', $user->id)
                      ->whereNot('depth', 0);
                })
                ->delete();

            DB::table('referral_paths')->insertUsing(
                ['ancestor_id', 'descendant_id', 'descendant_parent_id', 'depth'],
                DB::table('referral_paths')
                    ->where('ancestor_id', $user->id)
                    ->whereNot('depth', 0)
                    ->select([
                        DB::raw("{$new_anc['id']} as ancestor_id"),
                        'descendant_id',
                        DB::raw("$user->id as descendant_parent_id"),
                        DB::raw("depth + $relative_depths as depth"),
                    ])
            );

            $relative_depths++;
            $depths_new_parents--;
        }
    }

    // Delete orphaned rows from old parent chain
    if ($depths_old_parents > 0) {
        while ($depths_old_parents > 0) {
            $old_anc = $old_parents_tree[array_key_last($old_parents_tree) - ($depths_old_parents - 1)];

            ReferralPath::where('ancestor_id', $old_anc['id'])
                ->whereIn('descendant_id', $currentDescendant)
                ->delete();

            $depths_old_parents--;
        }
    }
}

Interested in how this was built? Reach out — happy to go deeper on any part of the architecture.

Comments