Building a CRM from Scratch: Architecture Decisions That Matter
Off-the-shelf CRMs like Salesforce and HubSpot work well until they do not — until you need a workflow that does not fit their data model, an integration that requires enterprise pricing, or a reporting view that their query builder cannot produce. Building a custom CRM gives you total control over the data model, user experience, and integration points. The trade-off is development time and ongoing maintenance. Having built several CRM systems for service businesses (including our own EssCode CRM), this article lays out the architecture decisions that determine whether your custom CRM becomes a competitive advantage or a maintenance burden.
Need help with django development? I provide django development for businesses ready to grow. Learn about my django development service or get in touch for a free consultation.
- Core Data Model
- Webhook Ingestion
- Permission Model
- Mobile-First Dashboard Design
Core Data Model
The data model is the foundation everything else builds on. Get it wrong and you will spend months refactoring. The core entities for a service business CRM are contacts (people), companies (organizations), deals (opportunities with stages and values), and activities (every interaction — calls, emails, meetings, notes). Resist the temptation to add entities upfront for features you might need later; start with these four and extend when real usage demands it.
class Contact(models.Model):
company = models.ForeignKey("Company", on_delete=models.SET_NULL, null=True, related_name="contacts")
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
phone = models.CharField(max_length=30, blank=True)
title = models.CharField(max_length=120, blank=True)
source = models.CharField(max_length=50, choices=SOURCE_CHOICES)
score = models.PositiveSmallIntegerField(default=0)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
indexes = [
models.Index(fields=["email"]),
models.Index(fields=["company", "-created"]),
models.Index(fields=["-score", "-created"]),
]
class Deal(models.Model):
contact = models.ForeignKey(Contact, on_delete=models.CASCADE, related_name="deals")
title = models.CharField(max_length=200)
value = models.DecimalField(max_digits=12, decimal_places=2)
stage = models.CharField(max_length=30, choices=STAGE_CHOICES)
probability = models.PositiveSmallIntegerField(default=0)
expected_close = models.DateField(null=True, blank=True)
closed_date = models.DateField(null=True, blank=True)
closed_won = models.BooleanField(null=True)
Two index decisions matter for CRM performance. First, index the fields you filter and sort by most frequently — email lookups, company-scoped contact lists, and score-ranked lead queues. Second, use a composite index on (company, -created) for the common pattern of showing a company's contacts in reverse chronological order. Without this index, that query requires a full table scan and sort on every company detail page.
Activity Timeline
The activity timeline is the most-used feature in any CRM. Sales reps live on this view — it shows every touchpoint with a contact in chronological order. The challenge is that activities come from many sources: manual notes, email conversations, phone calls, form submissions, and webhook events from external tools.
class Activity(models.Model):
class ActivityType(models.TextChoices):
NOTE = "note", "Note"
CALL = "call", "Phone Call"
EMAIL = "email", "Email"
MEETING = "meeting", "Meeting"
FORM = "form", "Form Submission"
WEBHOOK = "webhook", "External Event"
STAGE_CHANGE = "stage_change", "Stage Change"
contact = models.ForeignKey(Contact, on_delete=models.CASCADE, related_name="activities")
deal = models.ForeignKey(Deal, on_delete=models.SET_NULL, null=True, blank=True)
activity_type = models.CharField(max_length=20, choices=ActivityType.choices)
subject = models.CharField(max_length=200)
body = models.TextField(blank=True)
metadata = models.JSONField(default=dict, blank=True)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created"]
indexes = [
models.Index(fields=["contact", "-created"]),
models.Index(fields=["deal", "-created"]),
]
The metadata JSONField is essential for flexibility. A phone call activity stores duration and recording URL. An email stores message ID and thread ID. A webhook event stores the raw payload from the external system. This avoids a proliferation of model fields while keeping all data queryable through Django's JSON lookups. For the timeline view, fetch activities with a single query filtered by contact and ordered by creation date — the composite index makes this efficient even with millions of activity records.
First, index the fields you filter and sort by most frequently — email lookups, company-scoped contact lists, and score-ranked lead queues.
Deal Stage Automation
Manual deal management is error-prone. When a deal moves to "Proposal Sent," the system should automatically schedule a follow-up task, update the probability, and log the stage change. Django signals provide a clean hook for this automation without coupling it to your views.
from django.db.models.signals import pre_save
from django.dispatch import receiver
STAGE_PROBABILITIES = {
"new": 10, "qualified": 25, "proposal": 50,
"negotiation": 75, "closed_won": 100, "closed_lost": 0,
}
@receiver(pre_save, sender=Deal)
def handle_stage_change(sender, instance, **kwargs):
if not instance.pk:
return
try:
old = Deal.objects.get(pk=instance.pk)
except Deal.DoesNotExist:
return
if old.stage != instance.stage:
# Auto-set probability based on stage
instance.probability = STAGE_PROBABILITIES.get(instance.stage, instance.probability)
# Log the stage change as an activity
Activity.objects.create(
contact=instance.contact,
deal=instance,
activity_type="stage_change",
subject=f"Deal moved: {old.get_stage_display()} → {instance.get_stage_display()}",
metadata={"old_stage": old.stage, "new_stage": instance.stage},
)
# Handle terminal stages
if instance.stage in ("closed_won", "closed_lost"):
instance.closed_date = timezone.now().date()
instance.closed_won = instance.stage == "closed_won"
This signal-based approach means deal stage automation works regardless of how the stage changes — through the web interface, the admin, an API call, or a management command. The automation logic lives in one place, not scattered across multiple views. For more complex workflows (multi-step approval, conditional routing), consider a state machine library like django-fsm that enforces valid stage transitions and prevents invalid moves like jumping from "new" directly to "closed_won."
When a deal moves to "Proposal Sent," the system should automatically schedule a follow-up task, update the probability, and log the stage change.
Webhook Ingestion
Your CRM needs to receive data from external systems — form builders, email marketing platforms, phone systems, and payment processors. A well-designed webhook handler validates the payload, deduplicates events, and processes them asynchronously to avoid blocking the sender.
import hashlib
import hmac
@csrf_exempt
@require_POST
def webhook_receiver(request):
# HMAC verification
signature = request.headers.get("X-Webhook-Signature", "")
expected = hmac.new(
settings.WEBHOOK_SECRET.encode(),
request.body,
hashlib.sha256,
).hexdigest()
if not hmac.compare_digest(signature, expected):
return JsonResponse({"error": "Invalid signature"}, status=401)
payload = json.loads(request.body)
# Idempotency: skip duplicate events
event_id = payload.get("event_id", "")
if event_id and WebhookEvent.objects.filter(event_id=event_id).exists():
return JsonResponse({"status": "duplicate"}, status=200)
# Store raw event and process async
WebhookEvent.objects.create(
event_id=event_id,
source=payload.get("source", "unknown"),
event_type=payload.get("type", ""),
payload=payload,
)
# Process in background (Celery task)
process_webhook.delay(event_id)
return JsonResponse({"status": "accepted"}, status=202)
Always return 202 (Accepted) quickly and process the webhook asynchronously. External systems have timeout limits (typically 5-30 seconds), and if your handler takes too long, they will retry — leading to duplicate processing. The idempotency check on event_id prevents this, but quick acknowledgment is still best practice. For connecting your CRM to Google Ads conversion data, webhook ingestion is the foundation — lead events flow in, conversion events flow out.
Want expert help with this? Let's make it happen.
Get a Free ConsultationSearch with PostgreSQL Full-Text Search
CRM search needs to be fast and forgiving. Salespeople search by partial names, company fragments, email prefixes, and phone number snippets. PostgreSQL full-text search handles this with a combination of FTS for structured queries and trigram similarity for fuzzy matching.
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank, TrigramSimilarity
from django.db.models import Q
def search_contacts(query):
if not query:
return Contact.objects.none()
# Try FTS first for exact and stemmed matches
search_query = SearchQuery(query, search_type="websearch")
fts_results = (
Contact.objects.annotate(
search_rank=SearchRank(
SearchVector("first_name", "last_name", "email", "company__name"),
search_query,
)
)
.filter(search_rank__gte=0.1)
.order_by("-search_rank")
)
if fts_results.exists():
return fts_results
# Fall back to trigram similarity for fuzzy matches
return (
Contact.objects.annotate(
similarity=TrigramSimilarity("first_name", query)
+ TrigramSimilarity("last_name", query)
+ TrigramSimilarity("email", query)
)
.filter(similarity__gt=0.3)
.order_by("-similarity")
)
The two-tier approach gives you the best of both worlds: precise results when the query matches well, and fuzzy results when the user misspells a name or remembers only part of an email address. For CRMs with more than 100,000 contacts, add a GIN index on the search vector and a GiST index for trigram operations — without these indexes, search performance degrades linearly with data size.
Permission Model
CRM permissions must balance data access with privacy. Sales reps should see their own contacts and deals. Managers should see their team's pipeline. Executives need aggregate reports across all teams. The simplest effective pattern is role-based access with team scoping.
class CRMRole(models.TextChoices):
REP = "rep", "Sales Rep"
MANAGER = "manager", "Sales Manager"
ADMIN = "admin", "CRM Admin"
def get_visible_contacts(user):
profile = user.crm_profile
if profile.role == CRMRole.ADMIN:
return Contact.objects.all()
elif profile.role == CRMRole.MANAGER:
team_ids = profile.team.members.values_list("user_id", flat=True)
return Contact.objects.filter(
Q(owner__in=team_ids) | Q(owner=user)
)
else:
return Contact.objects.filter(owner=user)
Apply this scoping in every view, API endpoint, and report. The most common security mistake in CRM systems is forgetting to scope a single endpoint — allowing a rep to see all contacts by accessing the export endpoint directly. Use a custom queryset manager that applies scoping automatically, so developers cannot accidentally bypass it.
Reporting SQL
Sales teams need pipeline reports, conversion reports, and activity reports. These queries should run against the database directly — not against Django ORM constructs that generate inefficient SQL. Write raw SQL for complex reports and wrap them in Django management commands or view functions.
-- Pipeline report: deals by stage with weighted value
SELECT
stage,
COUNT(*) as deal_count,
SUM(value) as total_value,
SUM(value * probability / 100.0) as weighted_value,
AVG(EXTRACT(EPOCH FROM (NOW() - created)) / 86400) as avg_age_days
FROM deals
WHERE closed_date IS NULL
GROUP BY stage
ORDER BY
CASE stage
WHEN 'new' THEN 1
WHEN 'qualified' THEN 2
WHEN 'proposal' THEN 3
WHEN 'negotiation' THEN 4
END;
Cache these reports aggressively — a pipeline report that queries millions of rows should not run on every page load. Use Django's cache framework with a 5-minute TTL for dashboard widgets and generate detailed reports asynchronously via Celery tasks. The report runs once and is cached; subsequent requests see the cached version until it expires or is invalidated by a deal stage change.
Choosing Build vs Buy for Your Situation
Building a custom CRM makes sense when your sales process is genuinely unique, when you need deep integration with internal systems that off-the-shelf tools do not support, or when CRM licensing costs exceed development costs at your scale. For a 20-person sales team paying $150/user/month for Salesforce, that is $36,000/year — a custom CRM can be built for less than two years of licensing and runs indefinitely at hosting cost only.
Stick with off-the-shelf when your sales process fits standard CRM workflows, when you need the ecosystem of integrations that platforms like HubSpot provide, or when your team is small and would rather sell than maintain software. The build vs buy analysis we published goes deeper into the financial decision framework. If you decide to build, our CRM development service handles the architecture and implementation while your team focuses on selling.
Mobile-First Dashboard Design
Your sales team is not sitting at desks — they are in cars, at client sites, and on job sites. A CRM that does not work on a phone is a CRM that does not get used. Design mobile-first: the contact detail page should show name, phone (tap to call), and last activity above the fold. The deal board should work as a vertical list on mobile, not a Kanban board that requires horizontal scrolling. Forms should use large touch targets and minimize typing by offering smart defaults and selection lists. Test every view on a real phone, not just a browser's responsive mode — touch interactions, keyboard behavior, and scroll performance all differ from desktop simulation.
Related reading: Digital Marketing for Contractors: A Lead-Generation Playbook — a channel-by-channel playbook for contractors and home-service businesses that need steady leads.



Frequently asked questions
Is Django still a good choice for web development in 2027?
Yes. Django's batteries-included approach — authentication, ORM, admin, migrations, security middleware — makes it the most productive framework for business applications. Django 6.1 added composite primary keys, generated fields, and improved async support. The ecosystem continues growing with over 5,000 packages on PyPI.
When should I choose Django over Node.js or Next.js?
Choose Django when your application is data-heavy, needs a robust admin interface, requires complex business logic, or when your team knows Python. Choose Node.js/Next.js when you need server-side rendering for a React frontend, real-time features are the core product, or your team is JavaScript-first.
How do I deploy a Django application to production?
The standard production stack is: Gunicorn (application server) behind Nginx (reverse proxy), PostgreSQL (database), Redis (caching and sessions), systemd (process management), and Cloudflare or Let's Encrypt (HTTPS). Use environment variables for secrets and split settings into base, dev, and production files.
Full-stack developer specializing in Django, AI automation, and Google Ads management. Building production SaaS platforms and custom web applications for businesses across the US.