Database Architecture v1.0.0

Property Marketplace Prime

Comprehensive PostgreSQL database architecture for a modern real estate platform supporting buying, selling, and renting properties

35+ Database Tables
150+ Relationships
100% Production Ready

System Overview

A comprehensive real estate platform built on PostgreSQL

👥

User Management

Multi-role user system supporting buyers, renters, sellers, agents, and administrators with comprehensive profile management.

5 User Types Authentication Profiles
🏢

Agency System

Complete agency and agent management with licensing, verification, and performance tracking capabilities.

Agency Management Agent Profiles Performance Metrics
🏠

Property Listings

Flexible property management supporting both sales and rentals with rich media, amenities, and documents.

Sale & Rent Media Gallery Documents
📅

Inspections

Schedule and manage property viewings including open houses, private inspections, and virtual tours.

Scheduling Virtual Tours Registration
📝

Applications

Handle purchase offers and rental applications with document uploads and status tracking workflows.

Offers Applications Workflows
💰

Leases & Payments

Comprehensive lease management with automated rent payment tracking and late fee calculation.

Leases Payments Automation
📊
35+
Database Tables
🔗
150+
Foreign Keys
⚡
80+
Optimized Indexes
🎯
10
Main Sections

System Architecture

Layered architecture for scalability and maintainability

01

Application Layer

Web applications, mobile apps, admin dashboards, and agent portals providing user interfaces.

02

API Layer

RESTful APIs, GraphQL endpoints, and WebSocket connections for real-time updates.

03

Business Logic

Authentication, authorization, validation rules, and complex business workflows.

04

Database Layer

PostgreSQL with optimized schemas, indexes, and relationships for data persistence.

05

Caching Layer

Redis for session management, query result caching, and real-time data.

06

Storage Layer

Cloud storage for images, documents, and media files with CDN distribution.

Core Database Tables

Primary tables organized by functional domain

Table Name Category Purpose Key Features
users User Management Central user accounts and authentication Multi-role, verification, activity tracking
agencies User Management Real estate agencies and companies Licensing, ratings, property count
agent_profiles User Management Agent details and performance Specialization, reviews, sales tracking
properties Property Property listings and details Sale/rent, rich attributes, SEO slugs
locations Property Geographic location data Coordinates, hierarchical structure
inspections Transactions Property viewing schedules Open house, private, virtual tours
rental_applications Transactions Rental application submissions Document uploads, status workflow
leases Transactions Active rental agreements Terms, bond, payment schedule
rent_payments Transactions Rent payment tracking Due dates, late fees, status
property_reviews Engagement Property ratings and reviews 5-star rating, verification, moderation

Database Relationships

Understanding data connections and cardinality

1:1

One-to-One

Each record in Table A relates to exactly one record in Table B

users
↔
agent_profiles

A user can have one agent profile, and an agent profile belongs to one user.

1:N

One-to-Many

Each record in Table A can relate to multiple records in Table B

agencies
→
properties

An agency manages many properties, but each property belongs to one agency.

N:M

Many-to-Many

Records in both tables can relate to multiple records in each other

properties
↔
amenities

Properties have many amenities, and amenities belong to many properties.

Core Entity Relationships

👤

users

Central User Management

PK id UUID
UNIQUE email VARCHAR
FIELD role ENUM
FIELD is_verified BOOLEAN
→ properties
→ agent_profiles
→ leases
🏠

properties

Property Listings

PK id UUID
FIELD title VARCHAR
FIELD listing_type ENUM
FK owner_id → users
FK agency_id → agencies
→ media
→ inspections
↔ amenities
🏢

agencies

Real Estate Agencies

PK id UUID
FIELD name VARCHAR
UNIQUE license_number VARCHAR
FIELD rating DECIMAL
→ properties
→ agents
👨‍💼

agent_profiles

Agent Information

PK id UUID
FK user_id → users (1:1)
FK agency_id → agencies
FIELD specialization VARCHAR
→ properties
→ inspections
📄

leases

Rental Agreements

PK id UUID
FK property_id → properties
FK tenant_id → users
FIELD rent_amount DECIMAL
FIELD start_date DATE
→ payments
→ maintenance
📅

inspections

Property Viewings

PK id UUID
FK property_id → properties
FK agent_id → agents
FIELD inspection_type ENUM
FIELD scheduled_at TIMESTAMP
↔ attendees

Key Relationship Flows

Property Listing Flow
🏢
Agency
→
👨‍💼
Agent
→
🏠
Property
→
👤
Owner
Rental Process Flow
🏠
Property
→
📅
Inspection
→
📝
Application
→
📄
Lease
Payment Process Flow
👤
Tenant
→
📄
Lease
→
💰
Payment
→
👤
Owner

Indexing Strategy

Optimized indexes for high-performance queries

SQL
-- Primary Indexes for Property Search
CREATE INDEX idx_properties_status_listing 
ON properties(status, listing_type);

CREATE INDEX idx_properties_location 
ON properties(location_id);

CREATE INDEX idx_properties_sale_price 
ON properties(sale_price);

-- Composite Index for Featured Properties
CREATE INDEX idx_properties_featured 
ON properties(featured, status) 
WHERE status = 'active';

-- Location Search Indexes
CREATE INDEX idx_locations_postcode 
ON locations(postcode);

CREATE INDEX idx_locations_coordinates 
ON locations(latitude, longitude);

-- User Lookup Indexes
CREATE INDEX idx_users_email 
ON users(email);

CREATE INDEX idx_users_role 
ON users(role);
B-Tree

Default Indexes

Used for primary keys, foreign keys, and most common queries. Excellent for equality and range queries.

GIN

JSONB Indexes

Optimized for JSONB columns and full-text search. Perfect for flexible metadata and search filters.

GiST

Geospatial Indexes

Used for latitude/longitude coordinates. Enables efficient proximity and distance-based searches.

Security & Access Control

Multi-layered security approach

🔐

Authentication

Bcrypt password hashing with cost factor 12+, email verification, and password reset tokens with expiration.

🛡️

Row-Level Security

PostgreSQL RLS policies ensure users can only access data they're authorized to view and modify.

🔒

Data Encryption

PII fields encrypted at rest using pgcrypto extension. TLS/SSL for data in transit.

📝

Audit Logging

Comprehensive activity logs track all user actions with IP addresses, timestamps, and metadata.

🚫

SQL Injection Prevention

Parameterized queries and prepared statements prevent SQL injection attacks.

👤

Role-Based Access

Database roles (app_readonly, app_readwrite, app_admin) with granular permissions.

SQL - Row-Level Security Example
-- Enable Row-Level Security
ALTER TABLE properties ENABLE ROW LEVEL SECURITY;

-- Policy: Users can only see active properties or their own
CREATE POLICY property_visibility ON properties
FOR SELECT USING (
    status = 'active' 
    OR owner_id = current_user_id()
    OR listed_by_agent_id IN (
        SELECT id FROM agent_profiles 
        WHERE user_id = current_user_id()
    )
);

Performance Optimization

Strategies for high-performance operations

Query Optimization

Foundation

Use covering indexes, avoid N+1 queries, optimize joins, and leverage EXPLAIN ANALYZE for query planning.

Caching Strategy

Application Layer

Redis caching for frequently accessed data: property details (5 min TTL), search results (2 min TTL), user data (10 min TTL).

Connection Pooling

Infrastructure

PgBouncer configuration with transaction pooling mode, 25 connections per pool, max 1000 client connections.

Materialized Views

Database Layer

Pre-computed aggregations for complex queries: property search view, agent performance summary, analytics dashboard.

Scaling Strategy

From startup to enterprise scale

⬆️

Vertical Scaling

Scale up with more powerful hardware. Small: 4 cores/16GB, Medium: 8 cores/32GB, Large: 16 cores/64GB, Enterprise: 32+ cores/128+ GB.

Easy Implementation Immediate Results
↔️

Read Replicas

Horizontal scaling with PostgreSQL replication. Route read queries to replicas, writes to primary. Use pgpool-II for load balancing.

Read Performance High Availability
🗂️

Table Partitioning

Partition large tables by range or list. Properties by listing_type, activity_logs by date, improving query performance.

Large Tables Query Speed
🌐

Geographic Sharding

Shard database by geographic region or agency. Australia DB, USA DB, Europe DB. Each shard operates independently.

Global Scale Low Latency

Backup & Recovery

Disaster recovery and business continuity

🎯
1 Hour
Recovery Time (RTO)
💾
5 Min
Data Loss (RPO)
📅
Daily
Full Backups
🔄
24/7
WAL Archiving
Bash - Backup Commands
# Daily full backup
pg_dump -U postgres -F c -b -v \
  -f /backups/property_marketplace_$(date +%Y%m%d).backup \
  property_marketplace

# Compressed backup
pg_dump -U postgres -F c -Z 9 \
  property_marketplace > backup.dump

# Restore from backup
pg_restore -U postgres -d property_marketplace \
  -v /backups/latest.backup
📊

Full Backups

Daily full database backups at 2 AM, retained for 30 days. Monthly snapshots kept for 12 months.

📝

WAL Archiving

Continuous WAL (Write-Ahead Logging) archiving for point-in-time recovery. 7-day retention.

🔄

Replication

Synchronous replication to standby server for high availability and automatic failover.

API Integration

RESTful API endpoints and data access patterns

REST API Endpoints
// Property Endpoints
GET    /api/v1/properties              // List properties
GET    /api/v1/properties/:id          // Get property details
POST   /api/v1/properties              // Create property
PUT    /api/v1/properties/:id          // Update property
DELETE /api/v1/properties/:id          // Delete property

// Search & Filter
GET    /api/v1/properties/search       // Search properties
GET    /api/v1/properties/featured     // Featured listings

// User Authentication
POST   /api/v1/auth/register           // Register user
POST   /api/v1/auth/login              // Login
POST   /api/v1/auth/logout             // Logout

// Inspections
GET    /api/v1/inspections             // List inspections
POST   /api/v1/inspections/:id/register // Register for viewing