by faysal
ServicesSolutionsWorkPluginsBlogContact

by Faysal

AI Automation & Software Developer

hello@byfaysal.com

Navigate

ServicesSolutionsWorkBlogPluginsGuidesAboutResumeContactTools I Use

Services

Ecommerce PlatformsWordPress SolutionsWeb ApplicationsAutomationAI Solutions

From the Blog

WooCommerce vs ShopifyI Built a SaaS SoloZapier vs Make vs N8NView all articles →

Connect

EmailGitHubYouTubeInstagramLinkedInXUpworkFiverr

by Faysal

© 2026 Mostafa Faysal. Systems built with intention.

Privacy PolicyTermsAffiliate Disclosure
  1. Home
  2. /Blog
  3. /How I Built a Mission-Critical Election System With Zero Failures

saas · 18 min · 2026-06-08

How I Built a Mission-Critical Election System With Zero Failures

Building and deploying a live election platform at Sheraton Hotel, Dhaka — for KOICA. Atomic voting, real-time results, and zero room for error.

How I Built a Mission-Critical Election System With Zero Failures — featured imagesaas

TL;DR: I built a custom election management system for KOICA — an international organization — and deployed it at a live official election at Sheraton Hotel in Dhaka. The system handled voter registration via CSV upload, a multi-phase election lifecycle (nomination → voting → results), atomic vote recording with 5 layers of security, and real-time results displayed on large screens in front of the full audience. Zero integrity failures. Zero downtime. Built solo in 3 months with Django, React, and PostgreSQL.

Short answer: A room full of people watching a large screen. Every vote counted in real time. Every error visible to everyone. No second chance to get it right. That is what building a mission-critical system actually means — not the controlled environment of a staging server, but a live event where failure is public and immediate.

This is the story of building and deploying the KOICA Election System — a full-stack platform that ran a live organizational election from start to finish. It is the project that taught me the most about what "production-ready" actually means.

Why Custom Instead of Off-the-Shelf

KOICA needed an election system for an official organizational vote. They evaluated commercial election platforms and found the same problems every organization finds:

Per-voter pricing kills budgets. Commercial platforms like ElectionBuddy and Simply Voting charge $1-$5 per voter. For large organizational votes, this adds up quickly and repeats every election cycle.

No workflow customization. KOICA's election had a specific multi-phase flow: admin uploads eligible voters, nomination period opens, candidates are approved by administrators, voting opens for specific positions, results are calculated with specific rules. Off-the-shelf platforms offer their workflow, not yours.

Black box security. When votes happen inside a third-party platform, the organization has to trust that platform's security claims without verification. For an official election, that trust gap is a governance risk.

No live display integration. The election was happening at a physical event. Results needed to display on large screens in real time as voting progressed. No commercial platform offered this without expensive custom integration.

The decision was clear: build a system that matched their exact workflow, ran on their infrastructure, and gave them complete control and transparency.

The Architecture: 5 Phases, 5 Security Layers

The Election Lifecycle

The system enforces a strict phase-based lifecycle. Each phase opens specific capabilities and locks others:

Phase 1: SETUP
  └── Admin uploads voter CSV, creates positions, configures rules

Phase 2: NOMINATION
  └── Eligible members submit candidacy for positions
  └── Admin reviews and approves/rejects nominations

Phase 3: VOTING
  └── Approved voters cast one vote per position
  └── Real-time vote counting updates live dashboard

Phase 4: RESULTS
  └── Voting closes, final tallies calculated
  └── Results displayed on public screens

Phase 5: ARCHIVE
  └── Election data archived, audit trail preserved

The critical design decision was making phases server-enforced, not just UI-enforced. The frontend displays different interfaces per phase, but the backend rejects any request that does not belong to the current phase. A crafted API request to submit a vote during the nomination phase gets a 403 response — not because the button is hidden, but because the server validates the election state on every request.

5 Layers of Security

Election integrity is not a feature — it is the entire point. The system implements security at every layer:

Layer 1: Authentication. Every voter has a unique voter ID assigned during CSV upload. The ID is validated against the voter database before any action is permitted. No anonymous access to any election endpoint.

Layer 2: Phase validation. Every API endpoint checks the current election phase before processing. Vote submission endpoints return errors outside the voting phase. Nomination endpoints return errors outside the nomination phase. This is checked server-side on every request, not just on the frontend.

Layer 3: Eligibility check. Before recording a vote, the server verifies:

  • Is this voter registered for this election?
  • Has this voter already voted for this position?
  • Is this voter's account in good standing (not suspended)?
def validate_vote(voter_id, position_id, election_id):
    # Check voter exists and is eligible
    voter = Voter.objects.get(
        voter_id=voter_id,
        election_id=election_id,
        is_eligible=True
    )

    # Check election is in voting phase
    election = Election.objects.get(id=election_id)
    if election.phase != 'VOTING':
        raise ValidationError("Voting is not currently open")

    # Check voter has not already voted for this position
    existing_vote = Vote.objects.filter(
        voter=voter,
        position_id=position_id
    ).exists()

    if existing_vote:
        raise ValidationError("You have already voted for this position")

    return True

Layer 4: Database constraint. Even if the application layer fails (a race condition, a bug, a cosmic ray flipping a bit), the database itself prevents duplicate votes. A unique constraint on (voter_id, position_id) means the database will reject a duplicate vote at the storage level — the last line of defense.

ALTER TABLE votes
ADD CONSTRAINT unique_vote_per_position
UNIQUE (voter_id, position_id);

Layer 5: Immutability. Vote records are write-once. There is no UPDATE or DELETE endpoint for votes. No admin interface allows modifying a recorded vote. The database user has INSERT permission on the votes table but not UPDATE or DELETE. Once a vote is recorded, it exists permanently in the audit trail.

This layered approach means that a security failure at any single layer does not compromise the election. An attacker would need to bypass authentication, spoof the phase check, fool the eligibility validation, somehow bypass the database constraint, AND gain direct database access to modify a vote. Each layer is independent.

The Hardest Technical Problem: Atomic Vote Recording

The most critical operation in the entire system is recording a vote. It must be atomic — either the vote is fully recorded and the voter is marked as having voted, or nothing happens. A partial state (vote recorded but voter not marked, or voter marked but vote not recorded) would corrupt the election.

The Race Condition Threat

Imagine a voter double-clicks the "Vote" button. Two requests arrive at the server within milliseconds. Both requests check whether the voter has voted — both find "no." Both proceed to record a vote. The voter now has two votes for the same position.

The probability of this happening with a single user is low. But in an election with hundreds of voters casting ballots within a 30-minute window, the probability of at least one collision is significant.

The Solution: Database Transactions With Constraints

The vote recording operation runs inside a database transaction with the uniqueness constraint as the final safety net:

from django.db import transaction, IntegrityError

def cast_vote(voter_id, position_id, candidate_id):
    try:
        with transaction.atomic():
            # All validation inside the transaction
            voter = Voter.objects.select_for_update().get(
                voter_id=voter_id
            )

            # Record the vote
            Vote.objects.create(
                voter=voter,
                position_id=position_id,
                candidate_id=candidate_id,
                timestamp=timezone.now()
            )

            # Mark voter as having voted for this position
            VoterPositionStatus.objects.create(
                voter=voter,
                position_id=position_id,
                voted_at=timezone.now()
            )

        return {"status": "success", "message": "Vote recorded"}

    except IntegrityError:
        # Database constraint caught a duplicate — voter already voted
        return {"status": "error", "message": "You have already voted for this position"}

The select_for_update() call acquires a row-level lock on the voter record. The second request waits until the first transaction completes. When the second request proceeds, it finds the VoterPositionStatus record already exists and the IntegrityError prevents the duplicate.

This is the same pattern I used for concurrent bid handling in the WooCommerce Auction Engine — row-level locking to prevent race conditions in financial or high-integrity operations. The pattern works because it pushes the concurrency problem down to the database layer, which is designed to handle it correctly.

Real-Time Results on Large Screens

The results needed to display live on large screens at the event venue as voting happened. This created two requirements: a public-facing results page and a mechanism for pushing updates.

The Architecture

The results page is a standalone React view designed for large screen display:

  • Dark background with high-contrast text (readable from across a room)
  • Large font sizes optimized for viewing distance
  • Auto-refreshing vote counts without page reload
  • Bar chart visualization showing candidate standings per position
  • Animated transitions when vote counts change

The update mechanism is simple polling. Every 5 seconds, the results page fetches the current vote counts from the API. Given the context — an organizational election with hundreds of voters, not millions — polling is the right approach. WebSockets would add infrastructure complexity for no meaningful benefit at this scale.

// Results display polling
useEffect(() => {
    const interval = setInterval(async () => {
        const response = await fetch('/api/election/results/live/');
        const data = await response.json();
        setResults(data);
    }, 5000);

    return () => clearInterval(interval);
}, []);

The API endpoint that serves results is read-only and heavily cached. It queries the votes table, groups by position and candidate, counts, and returns. The query is efficient because the data model is simple and properly indexed.

The "Big Screen Moment"

The most stressful moment of the entire project was not a technical challenge. It was standing in the Sheraton Hotel ballroom watching the results page load on the projection screen for the first time during the actual election.

Every line of code I had written over the past three months was about to be tested in front of the people who were depending on it. There was no rollback, no hotfix window, no "we'll patch it later." If the vote counter showed the wrong number, everyone in the room would know immediately.

It worked. Votes appeared on screen within seconds of being cast. Totals updated smoothly. No errors, no freezes, no wrong numbers. The election completed, results were announced from the screen, and the system was archived.

That moment is why I build software. Not the code itself — the moment when the code becomes something real that people depend on.

What I Would Do Differently

Add an Offline Fallback

The system required internet connectivity. At a hotel with reliable WiFi, this was fine. But for elections in locations with unreliable connectivity — rural areas, developing regions, large conference centers with overloaded networks — the system needs a fallback.

If I built this again, I would add a Progressive Web App (PWA) layer that caches the voting interface locally and queues votes for sync when connectivity returns. The synchronization logic would be complex (resolving conflicts, verifying timestamps, handling votes cast during offline periods), but it would make the system usable in any environment.

Implement End-to-End Encryption for Votes

The current system stores votes in plaintext in the database. The database is secured, access is restricted, and the audit trail is immutable — but the administrator can technically see who voted for whom.

For higher-stakes elections where ballot secrecy is critical, I would implement a cryptographic voting protocol — encrypting votes with a public key that requires multiple election officials' private keys to decrypt. The results would still be tallied correctly (using homomorphic encryption or a mix-net protocol), but no single person could see individual votes.

This adds significant complexity and was not required for KOICA's organizational election, but it would be essential for government or union elections.

Build Reusable Multi-Election Support

The current system is built for a single election. Each deployment is a fresh instance. For organizations that run elections regularly — annual board votes, quarterly committee elections — the system should support multiple elections within a single deployment, with historical data, voter roll management across elections, and comparative analytics.

What This Project Taught Me

"Production-Ready" Has a Different Meaning for Mission-Critical Systems

Most web applications can tolerate bugs. A broken feature in a SaaS product means a support ticket and a fix next sprint. A broken feature in a live election means results that cannot be trusted.

Building for mission-critical means:

  • Every edge case is handled, not just the common paths
  • Security is layered, not single-point
  • Data integrity is enforced at the database level, not just the application level
  • The system is tested under conditions that mimic the real deployment (concurrent users, rapid submissions, network latency)
  • There is no post-launch patch strategy — it works on day one or it does not work

Solo Does Not Mean Unaccountable

I built this system alone — architecture, backend, frontend, deployment. But "solo" does not mean "without accountability." The KOICA team reviewed every feature, tested the voting flow, verified the security measures, and conducted a dry run before the live election.

The solo advantage was consistency. One developer means one architectural vision, one codebase style, one person who understands every line. There was no communication gap between the person who designed the security model and the person who implemented it — because they were the same person.

The Simplest Architecture Is the Most Reliable

Django, React, PostgreSQL. No microservices. No message queues. No distributed caching. No container orchestration. The stack is intentionally boring because boring technology has fewer failure modes.

For a system that needs to work perfectly for one critical event, simplicity is the highest form of engineering. Every additional service is an additional failure point. Every dependency is a risk.

The most reliable system I have ever built is also the simplest.

The Numbers

MetricValue
Development time3 months
RoleSole architect and engineer
TechnologyDjango, React, PostgreSQL, REST API, JWT
DeploymentLive at Sheraton Hotel, Banani, Dhaka
Vote integrity failuresZero
Downtime during electionZero
Security layers5 (auth, phase, eligibility, DB constraint, immutability)
Election phases5 (setup, nomination, voting, results, archive)
Real-time displayPolling every 5 seconds, optimized for large screens

Frequently Asked Questions

How much does a custom election system cost?

A basic election system (single election, straightforward voting, results display) costs $8,000-$15,000. A full-featured system with multi-position voting, nomination workflows, real-time display, and enterprise security costs $15,000-$30,000. Commercial per-voter platforms cost less upfront but more over time — and do not offer the customization or transparency of a custom build.

Can WordPress handle an election system?

For simple polls and surveys, WordPress with a forms plugin works fine. For a real election with voter authentication, vote integrity guarantees, and real-time results, WordPress is the wrong choice. Election systems need database-level constraints, atomic transactions, and custom security layers that WordPress's architecture does not naturally support. Django or a similar framework is better suited.

How do you prevent duplicate votes?

Five layers: authentication (unique voter ID), phase validation (votes only accepted during voting phase), eligibility check (server verifies voter has not voted for this position), database constraint (unique index on voter_id + position_id), and immutability (no update or delete operations on vote records). A duplicate vote would need to bypass all five layers simultaneously.

Can the system handle thousands of concurrent voters?

The current implementation handles hundreds of concurrent voters, which was sufficient for KOICA's organizational election. For thousands of concurrent voters, the same architecture scales with database connection pooling, read replicas for the results display, and horizontal application server scaling. The core vote recording logic (row-level locking with atomic transactions) handles concurrency correctly at any scale.

Is the system open source?

No — this was a custom build for KOICA. However, I build custom election and voting systems for organizations that need transparent, secure, and customizable election infrastructure. Reach out if your organization needs a voting platform tailored to your specific governance requirements.


Need a mission-critical system that works the first time? I build custom web applications for organizations where failure is not an option — from election platforms to enterprise SaaS to real-time bidding systems. Every system is designed, built, and deployed by one developer with full accountability. Book a free scoping call to discuss your project, or explore my web application development services.

Mostafa Faysal

Mostafa Faysal

Systems developer who builds ecommerce platforms, business automation, and SaaS products. 15+ production systems shipped.

→ Get a free audit→ See web-applications service