How to Design an Online Product Marketplace
Building a Production-Grade Multi-Vendor Platform — Listings, Search, Payments, Trust & Scale
1. Introduction & Why Marketplaces are Hard
An online product marketplace is one of the most complex distributed systems in e-commerce. Unlike a single-seller store, a marketplace connects millions of buyers with millions of sellers, each with their own inventory, pricing, shipping policies, and business rules. The platform must handle product discovery, trust and safety, payment processing with split payouts, logistics orchestration, and regulatory compliance across jurisdictions — all while delivering a seamless user experience that keeps both sides of the market engaged.
The fundamental challenge of a marketplace is the two-sided network effect. A marketplace with few sellers attracts few buyers, and vice versa. This chicken-and-egg problem means the platform must solve cold-start challenges, often by seeding initial inventory through partnerships, subsidies, or exclusive launches. Once the marketplace reaches critical mass, the network effect becomes a moat — but only if the platform maintains quality. Fake listings, counterfeit products, shipping fraud, and payment scams can destroy trust and collapse the marketplace just as quickly as it grew.
The technical complexity is staggering. Consider a simple transaction: a buyer in Germany purchases a handmade ceramics vase from a seller in Japan. The system must: validate the listing against prohibited items policy, check inventory availability, calculate shipping costs (with customs duties for international shipping), process payment in EUR, convert to JPY with FX rates, hold funds in escrow, generate a shipping label, track the package through multiple carriers, handle potential returns (who pays for return shipping?), manage VAT compliance for cross-border sales, and emit analytics events for both buyer and seller dashboards. Each of these steps involves multiple microservices, databases, and external integrations.
Real-world marketplaces operate at extraordinary scale. eBay processes over $100 billion in annual gross merchandise volume (GMV) across 1.7 billion listings. Amazon Marketplace accounts for over 60% of all e-commerce sales in the US. Etsy has 7.5 million active sellers and 96 million active buyers. These platforms have evolved over decades, but the core architectural patterns — search indexing, payment escrow, reputation systems, and logistics orchestration — remain consistent. This guide distills those patterns into a comprehensive design blueprint.
Real-World Case Studies
| Platform | Scale | Key Innovation | Revenue Model |
|---|---|---|---|
| eBay | 1.7B listings, $100B GMV | Auction pricing, trust through feedback | Insertion fees + final value fees |
| Amazon Marketplace | 60% of US e-commerce | FBA fulfillment, Buy Box algorithm | Referral fees + FBA fees |
| Etsy | 96M buyers, 7.5M sellers | Handmade/vintage niche, seller storytelling | Listing fees + transaction fees |
| Shopify (Marketplaces) | $197B GMV (2023) | Merchant-first, multi-channel | Subscription + payment processing |
| Alibaba/AliExpress | $1.2T GMV | Cross-border B2B, Alipay escrow | Membership + commission |
2. Functional & Non-Functional Requirements
Functional Requirements
- Seller Onboarding: Sellers can register, verify identity (KYC), set up storefronts, and configure payment/shipping preferences.
- Product Listings: Sellers create listings with titles, descriptions, multiple images, variants (size, color), attributes, pricing, and inventory quantities.
- Search & Discovery: Buyers search by keywords, filter by category, price, rating, location, and sort by relevance, price, recency, or popularity.
- Shopping Cart & Checkout: Buyers add items from multiple sellers, apply coupons/promotions, select shipping options, and complete payment.
- Payment Processing: Platform processes payments, holds in escrow, deducts fees, and disburses funds to sellers on schedule.
- Order Management: Both parties track order status from purchase through delivery. Sellers update tracking; buyers confirm receipt.
- Reviews & Ratings: Buyers rate products and sellers. Trust scores influence search ranking and Buy Box eligibility.
- Returns & Disputes: Buyers initiate returns; sellers accept/decline. Platform mediates disputes with evidence-based resolution.
- Analytics Dashboards: Sellers see sales, traffic, conversion, and inventory metrics. Buyers see purchase history and recommendations.
- Promotions: Sellers create deals, coupons, and flash sales. Platform runs site-wide events (Black Friday, Prime Day).
Non-Functional Requirements
| Requirement | Target | Rationale |
|---|---|---|
| Availability | 99.99% | Marketplace downtime directly loses revenue |
| Search Latency | < 200ms (p99) | Slow search increases bounce rates |
| Listing Creation | < 3 seconds | Sellers expect fast publishing |
| Payment Success Rate | > 99.5% | Failed payments lose sales |
| Concurrent Users | 10M+ during flash sales | Peak traffic during promotions |
| Data Consistency | Strong consistency for inventory & payments | Prevent overselling and double charges |
| Image Upload | < 5 seconds per image | Sellers upload many images per listing |
| Global Reach | Multi-region deployment | Low latency for international buyers |
3. Seller Onboarding and Verification
Seller onboarding is the marketplace's first impression. A smooth, trustworthy registration process determines whether a seller completes setup or abandons the platform. The onboarding flow must balance friction (to filter out bad actors) with speed (to avoid losing legitimate sellers). The process typically includes identity verification, business validation, payment setup, tax documentation, and storefront configuration.
KYC (Know Your Customer) Pipeline
Identity verification is critical for trust and regulatory compliance. The KYC pipeline verifies that sellers are who they claim to be and are legally allowed to sell. The process involves document verification (government-issued ID, business registration), address verification (utility bill, bank statement), bank account verification (micro-deposits or instant verification via Plaid), and tax ID validation (SSN/EIN for US, VAT number for EU).
flowchart LR
A[Seller Registration] --> B[Email/Phone Verification]
B --> C[Identity Document Upload]
C --> D[AI Document Verification]
D -->|Pass| E[Business Verification]
D -->|Fail| F[Manual Review Queue]
E -->|Individual| G[Tax ID Collection]
E -->|Business| H[Business Registration + Tax ID]
G --> I[Bank Account Verification]
H --> I
I --> J[Payment Setup]
J --> K[Storefront Configuration]
K --> L[Seller Dashboard Enabled]
F --> M[Support Agent Review]
M -->|Approved| E
M -->|Rejected| N[Rejection Email + Appeal Process]
Seller Tiers and Performance Metrics
Marketplaces typically implement seller tiers that unlock benefits as sellers demonstrate reliability. New sellers start at a basic tier with limited listing quotas and higher fees. As they complete transactions, maintain high ratings, and resolve issues promptly, they advance to higher tiers with lower fees, better search visibility, and access to premium features like promoted listings and bulk operations.
| Tier | Requirements | Benefits | Fee Discount |
|---|---|---|---|
| Bronze | Verified identity, 0-50 sales | Basic listing, standard support | 0% |
| Silver | 100+ sales, 4.5+ rating, <2% defect rate | 500 listings, promoted listings, priority support | 10% |
| Gold | 500+ sales, 4.7+ rating, <1% defect rate | Unlimited listings, featured seller badge, API access | 20% |
| Platinum | 2000+ sales, 4.8+ rating, <0.5% defect rate | Account manager, early access to new features, custom storefront | 30% |
Storefront Configuration
Each seller gets a customizable storefront where they can set their brand identity, policies, and preferences. This includes store name and logo, "About" description, shipping origin and policies (processing time, domestic/international shipping, free shipping thresholds), return policy (accepts returns, return window, who pays return shipping), payment methods accepted, and business hours and response time commitments.
4. Product Listing Management
Product listings are the atomic unit of a marketplace. A well-structured listing contains all the information a buyer needs to make a purchasing decision: title, description, images, variants, pricing, inventory, shipping, and category. The listing system must handle millions of concurrent updates, support rich media, and maintain data consistency across search indexes, caches, and analytics pipelines.
Listing Data Model
The listing data model must support product variations (size, color, material), seller-specific attributes, and marketplace-wide standards. A listing belongs to a seller, belongs to a category (which defines required attributes), and can have multiple SKUs (one per variant combination).
C#
public class Listing
{
public Guid Id { get; set; }
public Guid SellerId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Guid CategoryId { get; set; }
public ListingStatus Status { get; set; }
public decimal Price { get; set; }
public string Currency { get; set; }
public ListingType ListingType { get; set; } // Fixed, Auction, BestOffer
public List<ListingImage> Images { get; set; }
public List<ListingVariant> Variants { get; set; }
public Dictionary<string, string> Attributes { get; set; }
public InventoryInfo Inventory { get; set; }
public ShippingInfo Shipping { get; set; }
public ListingMetrics Metrics { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
public class ListingVariant
{
public Guid Id { get; set; }
public Guid ListingId { get; set; }
public string SKU { get; set; }
public Dictionary<string, string> VariantAttributes { get; set; }
public decimal PriceOverride { get; set; }
public int Quantity { get; set; }
public decimal Weight { get; set; }
public string Barcode { get; set; }
}
public class ListingImage
{
public Guid Id { get; set; }
public string Url { get; set; }
public string ThumbnailUrl { get; set; }
public int SortOrder { get; set; }
public bool IsPrimary { get; set; }
}
Multi-Image Upload Pipeline
Listing images go through a processing pipeline that ensures consistent quality and availability. When a seller uploads an image, the system validates file type and size, generates multiple resolutions (thumbnail 150x150, medium 600x600, large 1200x1200, original), creates WebP variants for modern browsers, runs AI-powered content moderation (detecting prohibited items, nudity, violence), extracts EXIF metadata for camera info, generates perceptual hashes for duplicate detection, and stores all variants in CDN-backed object storage.
flowchart TD
A[Seller Uploads Image] --> B[Validate File Type/Size]
B --> C[Store Original in S3]
C --> D[Image Processing Lambda]
D --> E[Generate Resized Variants]
D --> F[AI Content Moderation]
D --> G[EXIF Metadata Extraction]
D --> H[Perceptual Hash Generation]
E --> I[Store Variants in S3]
F -->|Clean| J[Mark Image Approved]
F -->|Flagged| K[Manual Review Queue]
I --> L[Update CDN Cache]
J --> M[Image Available on Listing]
K -->|Approved| J
K -->|Rejected| N[Notify Seller]
Variant Management
Product variants are essential for items that come in multiple options. A t-shirt might have sizes (S, M, L, XL) and colors (Red, Blue, Green), creating 16 possible SKU combinations. The system must track inventory per SKU, allow variant-specific pricing, and present a clean selection interface to buyers. When a buyer selects "Size: L, Color: Blue," the system looks up the corresponding SKU and checks inventory for that specific combination.
Listing Quality Score
Marketplaces assign quality scores to listings based on completeness, accuracy, and engagement. Higher quality scores improve search ranking and conversion. The score is computed from: title completeness (contains brand, key attributes), description quality (word count, formatting, detail), image count and quality (minimum 3 images, high resolution), attribute completeness (all required attributes filled), pricing competitiveness (compared to similar listings), and historical performance (click-through rate, conversion rate, return rate).
5. Product Search and Discovery
Search is the primary way buyers find products on a marketplace. A mediocre search experience means lost sales. The search system must handle millions of products, support full-text search with typo tolerance, provide faceted filtering, deliver personalized results, and return results in under 200 milliseconds. The system combines inverted indexes for text search, faceted indexes for filtering, vector embeddings for semantic search, and machine learning for ranking.
Search Architecture
flowchart LR
A[Buyer Query] --> B[Query Parser]
B --> C[Spell Correction]
B --> D[Tokenization]
B --> E[Synonym Expansion]
C --> F[Search Orchestrator]
D --> F
E --> F
F --> G[Full-Text Index]
F --> H[Faceted Index]
F --> I[Vector Index]
G --> J[Result Merging]
H --> J
I --> J
J --> K[Ranking Model]
K --> L[Personalization Layer]
L --> M[Results + Facets]
M --> N[Response < 200ms]
Elasticsearch Index Design
The search index is typically powered by Elasticsearch or OpenSearch. Each listing is indexed with analyzed text fields for full-text search, keyword fields for exact matching and faceting, numeric fields for price and quantity, date fields for recency, and nested objects for variants and seller information.
JSON
{
"mappings": {
"properties": {
"id": { "type": "keyword" },
"seller_id": { "type": "keyword" },
"title": { "type": "text", "analyzer": "custom_marketplace_analyzer" },
"description": { "type": "text", "analyzer": "custom_marketplace_analyzer" },
"category_id": { "type": "keyword" },
"price": { "type": "scaled_float", "scaling_factor": 100 },
"currency": { "type": "keyword" },
"status": { "type": "keyword" },
"condition": { "type": "keyword" },
"attributes": { "type": "nested", "properties": {
"name": { "type": "keyword" },
"value": { "type": "keyword" }
}},
"seller_rating": { "type": "float" },
"sales_count": { "type": "integer" },
"listing_created": { "type": "date" },
"tags": { "type": "keyword" },
"image_urls": { "type": "keyword", "index": false },
"embedding": { "type": "dense_vector", "dims": 768 }
}
}
}
Faceted Search
Faceted search allows buyers to narrow results by attributes like category, price range, brand, condition, rating, and location. Facets are computed aggregations over the search results. The system must dynamically generate facets based on the current result set — if you search for "laptop" in the "Electronics" category, the facets should show relevant brands (Dell, HP, Apple), price ranges ($500-$1000, $1000-$2000), and conditions (New, Refurbished).
Search Ranking Algorithm
The ranking algorithm determines the order of search results. It combines multiple signals: text relevance (TF-IDF or BM25 matching between query and title/description), popularity (sales velocity, view count, wishlist count), seller quality (rating, response rate, shipping speed), listing quality (completeness score, image quality), freshness (newer listings get a boost), pricing (competitive pricing relative to market), and personalization (buyer's past purchases, browsing history, location).
6. Category Taxonomy
The category taxonomy is the hierarchical structure that organizes all products on the marketplace. A well-designed taxonomy enables intuitive browsing, accurate search filtering, and seller-friendly listing creation. The taxonomy must support deep hierarchies (Electronics → Computers → Laptops → Gaming Laptops), category-specific attributes (laptops need RAM, CPU, screen size; clothing needs size, material), and taxonomy evolution (new categories emerge, old ones merge).
Taxonomy Data Model
C#
public class Category
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Slug { get; set; }
public Guid? ParentId { get; set; }
public int Depth { get; set; }
public List<CategoryAttribute> RequiredAttributes { get; set; }
public List<CategoryAttribute> OptionalAttributes { get; set; }
public string IconUrl { get; set; }
public int ListingCount { get; set; }
public bool IsActive { get; set; }
}
public class CategoryAttribute
{
public string Name { get; set; }
public AttributeType Type { get; set; }
public List<string> AllowedValues { get; set; }
public bool IsRequired { get; set; }
public bool IsFilterable { get; set; }
public bool IsSearchable { get; set; }
}
Category-Specific Attributes
Each category defines its own set of attributes that sellers must fill when listing a product. Electronics require technical specifications (processor, RAM, storage), clothing requires physical attributes (size, material, care instructions), and books require bibliographic data (ISBN, author, publisher, edition). These attributes power faceted search filters — when browsing "Laptops," buyers can filter by RAM (8GB, 16GB, 32GB), processor brand (Intel, AMD), and screen size (13", 15", 17").
| Category | Required Attributes | Filterable Attributes |
|---|---|---|
| Electronics - Laptops | Brand, CPU, RAM, Storage, Screen Size, OS | Brand, Price, RAM, CPU, Screen Size, Condition |
| Clothing - Shirts | Brand, Size, Color, Material, Pattern | Brand, Size, Color, Material, Price, Gender |
| Home - Furniture | Brand, Material, Dimensions, Weight Capacity | Brand, Material, Price, Color, Room |
| Books | Author, ISBN, Publisher, Publication Date, Language | Author, Genre, Language, Condition, Format |
7. Pricing Models
Online marketplaces support multiple pricing models to accommodate different selling strategies. The three primary models are fixed price (like Amazon), auction (like eBay), and best offer (negotiation). Each model has different technical requirements, user experiences, and economic implications.
Fixed Price Listings
Fixed price is the simplest model: the seller sets a price, the buyer pays it. The system must handle quantity management (decrement on purchase), price changes (update index, notify watchers), and sale prices (original price crossed out, discounted price shown). Sale prices enable promotions without changing the base listing price.
Auction Listings
Auction listings add temporal dynamics: the price changes over time as bidders compete. The system must handle bid placement (validate minimum increment, outbid notifications), proxy bidding (automatic incremental bids up to a maximum), auction end timing (precise end time, anti-sniping extensions), and winner determination (highest bidder wins, reserve price check).
C#
public class AuctionListing
{
public Guid ListingId { get; set; }
public decimal StartingPrice { get; set; }
public decimal ReservePrice { get; set; }
public decimal BidIncrement { get; set; }
public decimal CurrentPrice { get; set; }
public int TotalBids { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public Guid? CurrentHighBidderId { get; set; }
public List<Bid> BidHistory { get; set; }
}
public class Bid
{
public Guid Id { get; set; }
public Guid ListingId { get; set; }
public Guid BidderId { get; set; }
public decimal Amount { get; set; }
public decimal MaxProxyAmount { get; set; }
public DateTime BidTime { get; set; }
public bool IsAutoBid { get; set; }
}
Best Offer Listings
Best offer listings allow buyers to propose a price and sellers to accept, reject, or counter-offer. The system tracks offer history, manages expiration timers, and enforces maximum offer limits (sellers can set "auto-decline below $X"). This model works well for high-value items where negotiation is expected (antiques, art, used electronics).
8. Shopping Cart and Checkout
The shopping cart and checkout flow is where browsers become buyers. A marketplace cart is more complex than a single-seller store because it must handle items from multiple sellers, each with different shipping policies, processing times, and return policies. The checkout flow must calculate combined shipping, apply promotions, handle split payments, and ensure a smooth payment experience.
Cart Architecture
The cart is typically stored in Redis for fast read/write with session persistence. Each cart item references a listing and variant, and the cart groups items by seller for shipping calculation. The cart must handle real-time inventory checks (items may sell out while in cart), price changes (sellers may update prices), and promotion applicability (coupons may expire or change terms).
C#
public class ShoppingCart
{
public Guid Id { get; set; }
public Guid? UserId { get; set; }
public string SessionId { get; set; }
public List<CartGroup> SellerGroups { get; set; }
public List<CartPromotion> AppliedPromotions { get; set; }
public Money Subtotal { get; set; }
public Money TotalShipping { get; set; }
public Money TotalTax { get; set; }
public Money Total { get; set; }
}
public class CartGroup
{
public Guid SellerId { get; set; }
public string SellerName { get; set; }
public List<CartItem> Items { get; set; }
public ShippingOption SelectedShipping { get; set; }
public Money SellerSubtotal { get; set; }
public Money SellerShipping { get; set; }
}
public class CartItem
{
public Guid ListingId { get; set; }
public Guid VariantId { get; set; }
public string ProductName { get; set; }
public string ImageUrl { get; set; }
public int Quantity { get; set; }
public Money UnitPrice { get; set; }
public Money TotalPrice { get; set; }
}
Checkout Flow
flowchart TD
A[Review Cart] --> B[Select Shipping Addresses]
B --> C[Select Shipping Methods per Seller]
C --> D[Apply Promotions/Coupons]
D --> E[Review Order Summary]
E --> F[Select Payment Method]
F --> G[Validate Payment]
G -->|Success| H[Place Order]
G -->|Failed| I[Retry/Change Payment]
H --> J[Create Order per Seller]
J --> K[Reserve Inventory]
K --> L[Process Payment]
K --> M[Send Confirmation Emails]
K --> N[Notify Sellers]
K --> O[Update Analytics]
Split Payment
In a marketplace, the buyer pays the platform, but funds must be distributed to multiple sellers minus platform fees. The split payment model handles this by creating a payment intent per seller group. The buyer sees one total charge, but the platform internally creates separate payment records for each seller. After the payment clears, the platform holds funds in escrow and disburses to sellers according to the payout schedule.
9. Buyer Protection and Escrow
Buyer protection is the foundation of marketplace trust. Without it, buyers won't purchase from unknown sellers. The protection program guarantees that buyers receive the item as described or get a full refund. The escrow system holds payment until the buyer confirms receipt, creating a safe transaction window.
Escrow Flow
flowchart LR
A[Buyer Pays] --> B[Funds Held in Escrow]
B --> C[Seller Ships Item]
C --> D[Buyer Receives Item]
D --> E{Item as Described?}
E -->|Yes| F[Buyer Confirms Receipt]
E -->|No| G[Open Return/Dispute]
F --> H[Escrow Released to Seller]
G --> I[Platform Mediates]
I -->|Buyer Wins| J[Full Refund to Buyer]
I -->|Seller Wins| K[Funds Released to Seller]
I -->|Partial| L[Partial Refund]
Protection Policies
- Item Not Received (INR): If tracking shows delivery but buyer claims non-receipt, the platform investigates with carrier data. If no tracking or carrier confirms non-delivery, buyer gets a full refund.
- Item Not as Described (INAD): Buyer provides evidence (photos, description comparison) that the item differs from the listing. Seller can accept return or offer partial refund. If unresolved, platform mediates.
- Authorized Payment: If a buyer claims unauthorized payment, the platform checks for authentication records (3D Secure, address verification). Fraudulent claims are flagged and repeat offenders are banned.
- Protection Window: Typically 30-90 days from delivery. Claims filed after the window may be denied unless there are extenuating circumstances.
10. Seller Ratings and Reviews (Trust Score)
Seller ratings are the marketplace's reputation system. They create accountability for sellers and transparency for buyers. The trust score influences search ranking, Buy Box eligibility, and buyer confidence. The system must prevent fake reviews, handle retaliatory ratings, and provide meaningful aggregate metrics.
Rating Data Model
C#
public class SellerRating
{
public Guid Id { get; set; }
public Guid SellerId { get; set; }
public Guid ReviewerId { get; set; }
public Guid OrderId { get; set; }
public int OverallScore { get; set; }
public int QualityScore { get; set; }
public int CommunicationScore { get; set; }
public int ShippingSpeedScore { get; set; }
public string ReviewText { get; set; }
public List<string> ReviewPhotos { get; set; }
public bool IsVerifiedPurchase { get; set; }
public DateTime CreatedAt { get; set; }
}
public class SellerTrustScore
{
public Guid SellerId { get; set; }
public decimal OverallRating { get; set; }
public int TotalReviews { get; set; }
public int PositiveReviews { get; set; }
public int NegativeReviews { get; set; }
public decimal ResponseRate { get; set; }
public decimal OnTimeShippingRate { get; set; }
public decimal DefectRate { get; set; }
public decimal ReturnRate { get; set; }
public SellerTier Tier { get; set; }
}
Trust Score Calculation
The trust score is a weighted composite of multiple factors. It's not a simple average of star ratings — it weights recent reviews more heavily, factors in transaction metrics, and penalizes specific failure modes. The formula typically includes: weighted average of ratings (recent reviews weighted more), order defect rate (disputes, returns, cancellations), late shipment rate, response time to buyer messages, and positive feedback percentage.
11. Order Management Lifecycle
Order management tracks every transaction from purchase through delivery and potential returns. Each order follows a state machine with well-defined transitions. The system must handle concurrent updates, split orders (items from different sellers), partial shipments, and complex fulfillment scenarios.
Order State Machine
stateDiagram-v2
[*] --> Pending: Buyer Places Order
Pending --> Confirmed: Payment Authorized
Pending --> Cancelled: Payment Failed
Confirmed --> Processing: Seller Accepts
Confirmed --> Cancelled: Seller Declines
Processing --> Shipped: Seller Ships
Processing --> Cancelled: Seller Cancels
Shipped --> Delivered: Carrier Confirms
Shipped --> Returned: Buyer Initiates Return
Delivered --> Completed: Buyer Confirms / Auto-Confirm (14 days)
Delivered --> Disputed: Buyer Opens Dispute
Disputed --> Refunded: Platform Rules for Buyer
Disputed --> Completed: Platform Rules for Seller
Completed --> [*]
Cancelled --> Refunded: Refund Issued
Refunded --> [*]
Order Data Model
C#
public class Order
{
public Guid Id { get; set; }
public Guid BuyerId { get; set; }
public List<OrderGroup> SellerGroups { get; set; }
public Money TotalAmount { get; set; }
public Money PlatformFees { get; set; }
public Money SellerPayout { get; set; }
public OrderStatus Status { get; set; }
public PaymentInfo Payment { get; set; }
public List<OrderEvent> EventHistory { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
public class OrderGroup
{
public Guid GroupId { get; set; }
public Guid SellerId { get; set; }
public List<OrderItem> Items { get; set; }
public OrderGroupStatus Status { get; set; }
public ShippingInfo Shipping { get; set; }
public string TrackingNumber { get; set; }
public DateTime? ShippedAt { get; set; }
public DateTime? DeliveredAt { get; set; }
}
public class OrderEvent
{
public Guid Id { get; set; }
public OrderEventType EventType { get; set; }
public string Description { get; set; }
public string ActorId { get; set; }
public DateTime Timestamp { get; set; }
}
12. Shipping and Fulfillment
Shipping is the physical bridge between digital transaction and product delivery. The marketplace must support multiple fulfillment models: seller-fulfilled (seller ships directly), platform-fulfilled (warehouse network like Amazon FBA), and dropship (supplier ships directly to buyer). Each model has different cost structures, delivery speeds, and quality implications.
Shipping Rate Calculation
Shipping costs depend on package dimensions, weight, origin, destination, and carrier rates. The system must calculate real-time shipping rates by querying carrier APIs (UPS, FedEx, USPS, DHL) and applying seller-configured markup or free shipping thresholds. For international shipments, customs duties and import taxes must be estimated and potentially collected at checkout (DDP - Delivered Duty Paid).
C#
public class ShippingCalculator
{
private readonly ICarrierService _carrierService;
private readonly ITaxService _taxService;
public async Task<List<ShippingOption>> CalculateRates(
ShippingRequest request)
{
var rates = new List<ShippingOption>();
var sellerCarriers = await GetSellerCarriers(request.SellerId);
foreach (var carrier in sellerCarriers)
{
var carrierRates = await _carrierService.GetRates(
carrier.Id,
request.OriginAddress,
request.DestinationAddress,
request.Package);
foreach (var rate in carrierRates)
{
rates.Add(new ShippingOption
{
Carrier = carrier.Name,
Service = rate.ServiceName,
EstimatedDays = rate.DeliveryDays,
Cost = CalculateFinalCost(rate.BaseCost, request),
Currency = request.Currency
});
}
}
if (await QualifiesForFreeShipping(request))
{
rates.Insert(0, new ShippingOption
{
Carrier = "Free Shipping",
Service = "Standard",
EstimatedDays = 5,
Cost = Money.Zero(request.Currency)
});
}
return rates.OrderBy(r => r.EstimatedDays).ToList();
}
}
Fulfillment by Marketplace (FBM)
Platform fulfillment services (like Amazon FBA) handle storage, packing, shipping, and customer service for sellers. Sellers ship inventory to the platform's warehouse, and the platform manages the entire fulfillment process. Benefits include faster delivery (Prime-like), reduced seller operational burden, and higher Buy Box eligibility. The system must manage inventory intake, storage allocation, pick/pack/ship workflows, and seller inventory visibility.
13. Return and Refund Management
Returns are an inevitable part of e-commerce. The average return rate in online retail is 20-30%, and marketplaces must handle this gracefully. The return system must balance buyer protection (easy returns build trust) with seller protection (preventing abuse of return policies). The flow involves return initiation, label generation, item inspection, and refund processing.
Return Reasons and Policies
| Return Reason | Who Pays Return Shipping | Refund Type | SLA |
|---|---|---|---|
| Item Not as Described | Seller | Full refund | 3 business days |
| Item Damaged in Transit | Seller (or carrier claim) | Full refund or replacement | 3 business days |
| Changed Mind | Buyer | Full refund (minus shipping) | 5 business days |
| Wrong Item Received | Seller | Full refund + return label | 3 business days |
| Defective Product | Seller | Full refund or replacement | 3 business days |
Refund Processing
Refunds are processed through the original payment method. The system must handle: full refunds (return entire order), partial refunds (keep item with discount), shipping cost refunds (when seller is at fault), and currency conversion (refund in buyer's currency at current rate). Refunds are deducted from the seller's pending balance and may trigger seller alerts if refund rates exceed thresholds.
14. Dispute Resolution
Disputes arise when buyers and sellers can't resolve issues directly. The dispute resolution system must be fair, efficient, and evidence-based. It typically follows a structured process: initial contact, escalation to platform, evidence submission, platform ruling, and appeal. The goal is to resolve disputes quickly while minimizing platform intervention costs.
Dispute Resolution Flow
flowchart TD
A[Buyer Opens Dispute] --> B[Case Assigned to Mediator]
B --> C[Initial Contact Window - 48hrs]
C -->|Resolved| D[Case Closed]
C -->|Unresolved| E[Evidence Submission Phase]
E --> F[Buyer Submits Evidence]
E --> G[Seller Submits Evidence]
F --> H[Platform Review]
G --> H
H --> I{Ruling}
I -->|Buyer Wins| J[Full Refund]
I -->|Seller Wins| K[Funds Released to Seller]
I -->|Partial| L[Partial Refund]
J --> M[Case Closed]
K --> M
L --> M
M --> N{Appeal?}
N -->|Yes| O[Senior Mediator Review]
N -->|No| P[Final]
O --> Q[Final Ruling]
Evidence Types
- Communication History: All messages between buyer and seller through the platform messaging system.
- Listing Evidence: Screenshots of the original listing description, images, and attributes at time of purchase.
- Item Evidence: Photos/videos of the item showing defects, damage, or discrepancy from listing.
- Shipping Evidence: Carrier tracking data, delivery confirmation, signature confirmation.
- Return Evidence: Photos of returned item condition, package condition.
15. Payment Processing
Payment processing is the financial backbone of the marketplace. Unlike single-seller stores, marketplaces must handle split payments (one buyer payment distributed to multiple sellers), escrow (holding funds until delivery confirmation), and complex fee structures. The payment system must comply with PCI-DSS, handle chargebacks, support multiple payment methods, and manage multi-currency transactions.
Payment Architecture
flowchart LR
A[Buyer Initiates Payment] --> B[Payment Gateway]
B --> C{Payment Method}
C -->|Credit Card| D[Card Processor]
C -->|PayPal| E[PayPal API]
C -->|Apple Pay| F[Apple Pay API]
C -->|Bank Transfer| G[Bank API]
D --> H[Payment Authorized]
E --> H
F --> H
G --> H
H --> I[Split Payment Engine]
I --> J[Seller A Fund Hold]
I --> K[Seller B Fund Hold]
I --> L[Platform Fee Hold]
J --> M[Escrow Manager]
K --> M
L --> N[Platform Revenue]
M --> O{Delivery Confirmed?}
O -->|Yes| P[Release to Sellers]
O -->|No| Q[Hold Until Timeout]
Split Payment Implementation
C#
public class SplitPaymentService
{
public async Task<PaymentResult> ProcessSplitPayment(
SplitPaymentRequest request)
{
var auth = await _paymentGateway.Authorize(
request.BuyerId,
request.TotalAmount,
request.PaymentMethodId);
if (!auth.Success)
return PaymentResult.Failed(auth.ErrorMessage);
var splits = new List<PaymentSplit>();
foreach (var sellerGroup in request.SellerGroups)
{
var sellerAmount = sellerGroup.Subtotal;
var platformFee = CalculatePlatformFee(sellerAmount, sellerGroup.SellerId);
var shippingAmount = sellerGroup.ShippingCost;
var netToSeller = sellerAmount - platformFee + shippingAmount;
splits.Add(new PaymentSplit
{
SellerId = sellerGroup.SellerId,
GrossAmount = sellerAmount,
PlatformFee = platformFee,
ShippingCollected = shippingAmount,
NetPayout = netToSeller,
EscrowStatus = EscrowStatus.Held
});
}
var order = await _orderService.CreateOrder(request, splits);
await _escrowService.HoldFunds(auth.PaymentId, splits);
foreach (var split in splits)
{
await _notificationService.NotifySeller(
split.SellerId,
"New Order Received",
$"You have a new order for {split.NetPayout:C}");
}
return PaymentResult.Success(order.Id);
}
}
Payout Schedule
Marketplaces typically disburse seller funds on a regular schedule (daily, weekly, or bi-weekly) rather than immediately after each sale. This provides a buffer for returns and disputes, ensures sufficient funds for refund processing, and allows the platform to earn interest on held funds (a significant revenue stream for large marketplaces). The payout schedule is configurable per seller tier, with faster payouts for higher-tier sellers.
16. Seller Analytics Dashboard
The seller analytics dashboard provides sellers with actionable insights to optimize their business. It must process large volumes of transaction, traffic, and behavioral data in near real-time. The dashboard helps sellers understand what's selling, what's not, where traffic comes from, and how to improve their listings.
Key Metrics
| Metric | Description | Time Granularity |
|---|---|---|
| Revenue | Total sales amount (gross and net) | Hourly, Daily, Weekly, Monthly |
| Orders | Number of orders, average order value | Hourly, Daily, Weekly, Monthly |
| Conversion Rate | Views → Add to Cart → Purchase | Daily, Weekly |
| Traffic Sources | Search, Browse, External, Direct | Daily |
| Top Products | Best sellers by revenue and quantity | Daily, Weekly, Monthly |
| Inventory Levels | Stock per SKU, low stock alerts | Real-time |
| Customer Satisfaction | Average rating, review sentiment | Weekly, Monthly |
| Return Rate | Returns per listing, return reasons | Weekly, Monthly |
Analytics Data Pipeline
flowchart LR
A[Event Sources] --> B[Event Stream]
B --> C[Stream Processor]
C --> D[Real-time Aggregations]
C --> E[Batch Aggregations]
D --> F[Real-time Dashboard]
E --> G[Data Warehouse]
G --> H[BI Dashboard]
G --> I[ML Models]
I --> J[Recommendations]
I --> K[Pricing Insights]
17. Buyer Analytics and Recommendations
Buyer analytics power personalized shopping experiences. The system tracks browsing behavior, purchase history, wishlist activity, and search patterns to generate recommendations, targeted promotions, and personalized search results. Privacy compliance (GDPR, CCPA) is critical — all tracking must have user consent and respect data deletion requests.
Recommendation Engine
The recommendation system uses multiple algorithms: collaborative filtering (users who bought X also bought Y), content-based filtering (similar products to what you've viewed), trending (products gaining popularity), and contextual (seasonal, location-based). The system generates recommendations for different placements: product page "Customers also bought," homepage personalized grid, email "Recommended for you," and search result personalization.
C#
public class RecommendationEngine
{
private readonly ICollaborativeFilteringService _collabFilter;
private readonly IContentBasedFilterService _contentFilter;
private readonly ITrendingService _trendingService;
public async Task<List<ProductRecommendation>> GetRecommendations(
Guid userId, string context, int count = 20)
{
var recommendations = new List<ProductRecommendation>();
var userProfile = await _userProfileService.GetProfile(userId);
var collabResults = await _collabFilter.GetSimilarUsers(
userId, userProfile.PurchaseHistory);
recommendations.AddRange(
collabResults.Take(count * 40 / 100)
.Select(r => r.ToRecommendation(RecommendationSource.Collaborative)));
var contentResults = await _contentFilter.GetSimilarProducts(
userProfile.ViewedProducts, userProfile.PreferredAttributes);
recommendations.AddRange(
contentResults.Take(count * 30 / 100)
.Select(r => r.ToRecommendation(RecommendationSource.ContentBased)));
var trendingResults = await _trendingService.GetTrending(
userProfile.PreferredCategories, context);
recommendations.AddRange(
trendingResults.Take(count * 20 / 100)
.Select(r => r.ToRecommendation(RecommendationSource.Trending)));
var dealResults = await _promotionService.GetPersonalizedDeals(
userProfile, userProfile.PreferredCategories);
recommendations.AddRange(
dealResults.Take(count * 10 / 100)
.Select(r => r.ToRecommendation(RecommendationSource.Promotion)));
return recommendations
.GroupBy(r => r.ProductId)
.Select(g => g.OrderByDescending(r => r.Score).First())
.OrderByDescending(r => r.Score)
.Take(count)
.ToList();
}
}
18. Promotions and Deals
Promotions drive sales velocity and attract buyers. The marketplace supports both seller-initiated promotions (individual seller coupons, sale events) and platform-wide promotions (Black Friday, holiday sales). The promotion engine must handle complex rules, prevent stacking abuse, and accurately calculate discounts across multi-seller orders.
Promotion Types
| Promotion Type | Description | Example |
|---|---|---|
| Percentage Discount | Reduced price by percentage | 20% off all listings |
| Fixed Amount Off | Dollar amount discount | $10 off orders over $50 |
| Buy One Get One | Free item with purchase | Buy 1 get 1 50% off |
| Free Shipping | Waive shipping cost | Free shipping on orders over $25 |
| Flash Sale | Time-limited deep discount | 50% off for 2 hours |
| Coupon Code | Code-based discount | SUMMER20 for 20% off |
| Loyalty Reward | Discount for repeat buyers | 10% off for Gold members |
Promotion Engine Architecture
C#
public class PromotionEngine
{
public async Task<PromotionResult> ApplyPromotions(
ShoppingCart cart, List<PromotionCode> appliedCodes)
{
var result = new PromotionResult();
var eligiblePromotions = await GetEligiblePromotions(cart);
foreach (var promo in eligiblePromotions.Where(p => p.IsAutomatic))
{
if (promo.Condition.Evaluate(cart))
{
result.AddDiscount(promo, CalculateDiscount(promo, cart));
}
}
foreach (var group in cart.SellerGroups)
{
var sellerPromos = await GetSellerPromotions(group.SellerId);
foreach (var promo in sellerPromos)
{
if (promo.Condition.Evaluate(group))
{
result.AddSellerDiscount(group.SellerId,
CalculateSellerDiscount(promo, group));
}
}
}
foreach (var code in appliedCodes)
{
var promo = await ValidateCouponCode(code, cart);
if (promo != null)
{
result.AddDiscount(promo, CalculateDiscount(promo, cart));
}
}
result.EnforceStackingRules();
return result;
}
}
19. Inventory Management
Inventory management prevents overselling and ensures accurate stock levels across the marketplace. The system must handle real-time inventory updates, concurrent purchase attempts, multi-channel inventory (seller sells on multiple platforms), and low-stock alerts. Overselling is catastrophic for marketplace trust — if a buyer purchases an item that's out of stock, the entire transaction must be canceled.
Inventory Reservation System
When a buyer adds an item to the cart or initiates checkout, the system temporarily reserves inventory. This reservation is time-limited (e.g., 10 minutes for cart, 15 minutes for checkout) to prevent inventory lock-up by abandoned carts. The reservation system uses distributed locking to prevent race conditions when two buyers attempt to purchase the last item simultaneously.
C#
public class InventoryService
{
private readonly IDistributedLock _lockProvider;
private readonly IInventoryRepository _repository;
public async Task<InventoryResult> ReserveInventory(
Guid variantId, int quantity, TimeSpan reservationDuration)
{
var lockKey = $"inventory:{variantId}";
using var lockHandle = await _lockProvider.AcquireAsync(
lockKey, TimeSpan.FromSeconds(30));
var inventory = await _repository.GetInventory(variantId);
if (inventory.AvailableQuantity < quantity)
{
return InventoryResult.Insufficient(inventory.AvailableQuantity);
}
var reservation = new InventoryReservation
{
VariantId = variantId,
Quantity = quantity,
ExpiresAt = DateTime.UtcNow.Add(reservationDuration),
Status = ReservationStatus.Active
};
await _repository.CreateReservation(reservation);
inventory.AvailableQuantity -= quantity;
inventory.ReservedQuantity += quantity;
await _repository.UpdateInventory(inventory);
await _scheduler.ScheduleJob<ReservationExpiryJob>(
reservation.Id, reservation.ExpiresAt);
return InventoryResult.Reserved(reservation.Id);
}
public async Task ConfirmReservation(Guid reservationId)
{
var reservation = await _repository.GetReservation(reservationId);
reservation.Status = ReservationStatus.Confirmed;
await _repository.UpdateReservation(reservation);
var inventory = await _repository.GetInventory(reservation.VariantId);
inventory.ReservedQuantity -= reservation.Quantity;
inventory.CommittedQuantity += reservation.Quantity;
await _repository.UpdateInventory(inventory);
}
}
20. Multi-Currency and International Selling
Global marketplaces must handle multiple currencies, languages, and regulatory requirements. Buyers should see prices in their local currency, sellers can price in their preferred currency, and the platform handles conversion at competitive rates. International selling introduces customs, duties, and import taxes that must be calculated and collected at checkout.
Currency Management
C#
public class CurrencyService
{
private readonly IExchangeRateProvider _rateProvider;
public async Task<Money> Convert(Money amount, string targetCurrency)
{
if (amount.Currency == targetCurrency)
return amount;
var rate = await _rateProvider.GetRate(amount.Currency, targetCurrency);
var fee = amount.Value * _conversionFeeRate;
var convertedValue = (amount.Value - fee) * rate.Rate;
return new Money
{
Value = Math.Round(convertedValue, 2),
Currency = targetCurrency,
ExchangeRate = rate.Rate,
ConversionFee = fee
};
}
public async Task<PricingInfo> GetLocalizedPricing(
Guid listingId, string buyerCurrency)
{
var listing = await _listingService.Get(listingId);
var basePrice = new Money(listing.Price, listing.Currency);
return new PricingInfo
{
OriginalPrice = basePrice,
DisplayPrice = await Convert(basePrice, buyerCurrency),
EstimatedImportTax = await CalculateImportTax(basePrice, buyerCurrency),
TotalEstimatedCost = await CalculateTotalWithDuties(basePrice, buyerCurrency)
};
}
}
International Shipping Considerations
- Customs Declarations: Accurate HS (Harmonized System) codes for customs forms, item descriptions, and declared values.
- Import Duties: DDP (Delivered Duty Paid) where seller/platform collects duties at checkout, or DDU (Delivered Duty Unpaid) where buyer pays on delivery.
- Prohibited Items: Some items can't be shipped internationally (certain electronics, food, plants). The system must filter available shipping destinations per listing.
- Shipping Carriers: International carriers (DHL, FedEx International, UPS Worldwide) with tracking and customs brokerage.
21. Tax Calculation
Tax calculation in e-commerce is notoriously complex. In the US, sales tax varies by state, county, and city, with different rates for different product categories. In the EU, VAT (Value Added Tax) must be collected and remitted based on buyer location. The marketplace may be responsible for collecting and remitting taxes on behalf of sellers (marketplace facilitator laws).
Tax Architecture
flowchart TD
A[Order Placed] --> B[Tax Calculation Service]
B --> C[Determine Nexus]
C --> D[Look Up Tax Rate]
D --> E[Apply Tax Rules]
E --> F[Calculate Tax Amount]
F --> G[Include in Order Total]
G --> H[Store Tax Record]
H --> I[Report to Tax Authority]
US Sales Tax
After the 2018 South Dakota v. Wayfair Supreme Court decision, states can require out-of-state sellers to collect sales tax if they have economic nexus (typically $100,000 in sales or 200 transactions). Marketplace facilitator laws in 45+ states require the marketplace itself to collect and remit sales tax on behalf of sellers. The system must: determine if nexus exists in each state, apply the correct state + county + city tax rate, handle product-specific exemptions (e.g., groceries exempt in some states), and generate tax reports for each jurisdiction.
EU VAT
For EU cross-border sales, the OSS (One-Stop Shop) scheme allows sellers to register in one EU country and remit VAT for all EU sales. The system must: determine buyer's country, apply the correct VAT rate (standard, reduced, or zero), show VAT-inclusive prices (required in EU), and generate VAT reports for the seller's OSS filing.
C#
public class TaxCalculator
{
private readonly ITaxRateProvider _rateProvider;
private readonly ITaxRulesEngine _rulesEngine;
public async Task<TaxResult> CalculateTax(Order order, Address shippingAddress)
{
var result = new TaxResult();
foreach (var item in order.Items)
{
var taxCategory = await _rulesEngine.GetTaxCategory(
item.ProductId, shippingAddress.Country);
var taxRate = await _rateProvider.GetRate(
shippingAddress.Country,
shippingAddress.State,
shippingAddress.City,
taxCategory);
var itemTax = item.Subtotal * taxRate.Rate;
result.AddLineItemTax(new TaxLineItem
{
ProductId = item.ProductId,
TaxableAmount = item.Subtotal,
TaxRate = taxRate.Rate,
TaxAmount = itemTax,
TaxType = taxRate.TaxType
});
}
if (order.Buyer.IsTaxExempt)
{
result.ApplyExemption(order.Buyer.TaxExemptionId);
}
result.TotalTax = result.LineItems.Sum(l => l.TaxAmount);
return result;
}
}
22. Fraud Detection
Fraud costs marketplaces billions annually. Common fraud types include fake listings (scammers list items they don't have), shill bidding (sellers bid on their own auctions to inflate prices), account takeover (compromised buyer/seller accounts), payment fraud (stolen credit cards), and refund abuse (serial returners). The fraud detection system must identify and prevent these threats in real-time while minimizing false positives that block legitimate transactions.
Fraud Detection Pipeline
flowchart LR
A[Transaction Event] --> B[Risk Scoring Engine]
B --> C{Risk Score}
C -->|Low| D[Approve]
C -->|Medium| E[Step-up Verification]
C -->|High| F[Block + Review]
E -->|Pass| D
E -->|Fail| F
F --> G[Manual Review]
G -->|Legitimate| D
G -->|Fraudulent| H[Block Account]
Fraud Signals
| Fraud Type | Signals | Prevention |
|---|---|---|
| Fake Listings | Stock photos, too-good-to-be-true prices, new seller, no reviews | Image verification, price anomaly detection, seller vetting |
| Shill Bidding | Bidding from same IP/device as seller, bidding pattern anomalies | IP fingerprinting, bidding pattern analysis, account linkage detection |
| Account Takeover | Login from new device/location, password change followed by purchase | MFA, device fingerprinting, behavioral analysis |
| Payment Fraud | Stolen card BIN mismatch, AVV/CVV failures, velocity checks | 3D Secure, address verification, velocity limits |
| Return Abuse | High return rate, returning used/damaged items, serial returns | Return history tracking, item condition verification, buyer bans |
ML-Based Fraud Detection
C#
public class FraudDetectionService
{
private readonly IFraudModel _mlModel;
private readonly IRiskRuleEngine _ruleEngine;
public async Task<FraudResult> EvaluateTransaction(
TransactionContext context)
{
var features = await ExtractFeatures(context);
var mlScore = await _mlModel.PredictFraudProbability(features);
var ruleScore = await _ruleEngine.EvaluateRules(context);
var combinedScore = CombineScores(mlScore, ruleScore);
if (combinedScore < 0.2)
return FraudResult.Approved(combinedScore);
if (combinedScore < 0.6)
return FraudResult.StepUpRequired(combinedScore,
GetRequiredVerification(context));
return FraudResult.Blocked(combinedScore,
GetBlockReasons(features));
}
private async Task<FraudFeatures> ExtractFeatures(
TransactionContext context)
{
return new FraudFeatures
{
BuyerAccountAge = context.Buyer.AccountAge,
BuyerTransactionHistory = await GetTransactionHistory(
context.Buyer.Id),
ListingPricePercentile = await GetPricePercentile(
context.Listing),
SellerTrustScore = context.Seller.TrustScore,
DeviceFingerprint = context.DeviceFingerprint,
IPAddressGeolocation = context.IPGeo,
TimeSinceLastTransaction = await GetTimeSinceLastTxn(
context.Buyer.Id),
IsInternationalTransaction = context.IsCrossBorder
};
}
}
23. Monitoring, Security & Compliance
Marketplaces handle sensitive financial data, personal information, and high-volume transactions. Robust monitoring, security, and compliance practices are non-negotiable. A single data breach can destroy marketplace trust and result in regulatory fines.
Monitoring Architecture
flowchart TD
A[Application Services] --> B[Metrics Collection]
A --> C[Log Collection]
A --> D[Trace Collection]
B --> E[Prometheus/Grafana]
C --> F[ELK Stack]
D --> G[Jaeger/Zipkin]
E --> H[Dashboards & Alerts]
F --> H
G --> H
H --> I[PagerDuty/OpsGenie]
H --> J[Slack Notifications]
H --> K[Runbook Automation]
Key Monitoring Metrics
| Category | Metric | Alert Threshold |
|---|---|---|
| Availability | Service uptime, error rate | < 99.99% or > 0.1% errors |
| Performance | Search latency (p99), API latency (p99) | > 200ms search, > 500ms API |
| Business | Conversion rate, cart abandonment, GMV | > 10% drop from baseline |
| Payment | Payment success rate, chargeback rate | < 99.5% success, > 1% chargeback |
| Search | Zero-result queries, search CTR | > 5% zero-result, < 2% CTR |
| Fraud | Fraud detection rate, false positive rate | > 5% fraud or > 2% false positive |
Security Requirements
- PCI-DSS Compliance: Mandatory for handling credit card data. Implement network segmentation, encryption at rest and in transit, access controls, and regular security audits.
- GDPR/CCPA Compliance: Data encryption, consent management, right to deletion, data portability, breach notification within 72 hours.
- SOC 2 Type II: Annual audit of security controls, availability, processing integrity, confidentiality, and privacy.
- Encryption: AES-256 for data at rest, TLS 1.3 for data in transit, field-level encryption for PII and payment data.
- Access Control: Role-based access control (RBAC), multi-factor authentication for admin access, least-privilege principle.
24. Cost Estimation
Running a marketplace at scale involves significant infrastructure costs. Understanding these costs is essential for pricing strategy, investor conversations, and operational planning. The cost model varies based on scale, but the following provides a framework for estimation.
Monthly Cost Breakdown (1M GMV/month marketplace)
| Service | Configuration | Monthly Cost (USD) |
|---|---|---|
| Application Servers | 8x c5.2xlarge (ECS/EKS) | $4,000 |
| Primary Database | r5.4xlarge Multi-AZ (PostgreSQL) | $3,500 |
| Read Replicas | 3x r5.2xlarge | $4,500 |
| Redis Cluster | 3x r5.xlarge nodes | $1,500 |
| Elasticsearch | 6x m5.2xlarge nodes | $5,400 |
| CDN (CloudFront) | 10TB transfer/month | $850 |
| Object Storage (S3) | 5TB stored, 50TB transfer | $1,500 |
| Message Queue (SQS/SNS) | 100M messages/month | $50 |
| Search (OpenSearch) | 3x m5.xlarge | $1,500 |
| ML Inference | Recommendation + fraud models | $2,000 |
| Monitoring (Datadog) | Full stack monitoring | $3,000 |
| Third-Party Services | Tax, payments, shipping APIs | $5,000 |
| Total Infrastructure | $33,300 |
25. API Design
The marketplace API must serve multiple clients (web app, mobile app, seller tools, partner integrations) with a consistent, versioned, and well-documented interface. The API follows RESTful conventions with JSON payloads, OAuth 2.0 authentication, rate limiting, and comprehensive error handling.
Core API Endpoints
| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /api/v1/sellers/register | Seller registration | None |
| GET | /api/v1/sellers/{id} | Get seller profile | Public |
| POST | /api/v1/listings | Create listing | Seller |
| PUT | /api/v1/listings/{id} | Update listing | Seller (owner) |
| DELETE | /api/v1/listings/{id} | Delete listing | Seller (owner) |
| GET | /api/v1/search | Search listings | Public |
| GET | /api/v1/listings/{id} | Get listing details | Public |
| POST | /api/v1/cart/items | Add to cart | Buyer |
| GET | /api/v1/cart | Get cart | Buyer |
| POST | /api/v1/orders/checkout | Checkout | Buyer |
| GET | /api/v1/orders/{id} | Get order details | Buyer/Seller |
| POST | /api/v1/orders/{id}/confirm-receipt | Confirm receipt | Buyer |
| POST | /api/v1/reviews | Submit review | Buyer (verified purchase) |
| GET | /api/v1/sellers/{id}/analytics | Get seller analytics | Seller (owner) |
Search API Example
C#
[ApiController]
[Route("api/v1/search")]
public class SearchController : ControllerBase
{
private readonly ISearchService _searchService;
[HttpGet]
public async Task<ActionResult<SearchResponse>> Search(
[FromQuery] SearchRequest request)
{
var result = await _searchService.Search(new SearchQuery
{
Query = request.Q,
Category = request.Category,
MinPrice = request.MinPrice,
MaxPrice = request.MaxPrice,
Brand = request.Brand,
Condition = request.Condition,
SellerRating = request.MinRating,
SortBy = request.SortBy ?? "relevance",
Page = request.Page ?? 1,
PageSize = request.PageSize ?? 24
});
return Ok(new SearchResponse
{
Results = result.Items.Select(i => new SearchResult
{
Id = i.Id,
Title = i.Title,
Price = i.Price,
Currency = i.Currency,
ImageUrl = i.PrimaryImageUrl,
SellerName = i.SellerName,
SellerRating = i.SellerRating,
Condition = i.Condition
}),
TotalCount = result.TotalCount,
Facets = result.Facets,
Page = result.Page,
PageSize = result.PageSize
});
}
}
Rate Limiting
Implement rate limiting to protect against abuse and ensure fair resource allocation. Different endpoints have different limits: search (100 requests/minute per IP), listing creation (10 requests/minute per seller), cart operations (30 requests/minute per user), and API integrations (1000 requests/minute per API key). Use Redis-based sliding window counters for distributed rate limiting.
26. Testing Strategy
A marketplace requires comprehensive testing across functional, performance, security, and chaos engineering dimensions. The complexity of multi-seller transactions, payment processing, and real-time inventory demands rigorous test coverage.
Test Pyramid
flowchart TD
A[Unit Tests - 70%] --> B[Integration Tests - 20%]
B --> C[E2E Tests - 8%]
C --> D[Manual Exploratory - 2%]
Test Categories
| Category | Scope | Tools | Coverage Target |
|---|---|---|---|
| Unit Tests | Business logic, price calculation, tax rules | xUnit, Moq | 80%+ |
| Integration Tests | Database queries, API integrations, search indexing | Testcontainers, WireMock | Critical paths |
| Contract Tests | API contracts between services | Pact | All API endpoints |
| E2E Tests | Complete purchase flow, seller onboarding | Playwright, Cypress | Top 20 user journeys |
| Performance Tests | Search latency, checkout throughput, flash sale simulation | k6, Gatling | <200ms p99 search |
| Security Tests | OWASP Top 10, PCI-DSS validation | OWASP ZAP, SonarQube | All critical vulns |
| Chaos Tests | Service failure, database failover, network partition | Chaos Monkey, Litmus | Monthly exercises |
Key Test Scenarios
- Multi-Seller Cart: Add items from 5 sellers, verify shipping calculation per seller, verify split payment, verify order creation per seller.
- Inventory Race Condition: Simulate 100 concurrent buyers purchasing the last item. Verify exactly one succeeds, rest receive "out of stock" error.
- Auction Sniper: Place bid in final 5 seconds. Verify anti-sniping extension triggers and auction extends by configured duration.
- Payment Failure Recovery: Simulate payment failure after order creation. Verify order is cancelled, inventory is released, and no charge is made.
- Return Flow: Create order, deliver, initiate return, ship back, confirm receipt, verify refund amount and seller deduction.
27. Interview Q&A Deep Dive
System design interviews for marketplace roles test your understanding of distributed systems, data consistency, and business trade-offs. Here are the most commonly asked questions with detailed answers.
Q1: How do you prevent overselling when multiple buyers purchase the last item simultaneously?
Q2: How would you design the search ranking algorithm?
Q3: How do you handle the two-sided cold-start problem?
Q4: How do you design the payment escrow system?
Q5: How do you scale search to handle millions of listings with sub-200ms latency?
Q6: How do you detect and prevent shill bidding?
Q7: How do you handle international sales with different currencies, taxes, and regulations?
Q8: How do you design the Buy Box algorithm (Amazon-style)?
28. Seller Reputation and Trust Score Engine
The seller trust score determines search ranking, Buy Box eligibility, and buyer confidence. The scoring system must balance multiple signals — transaction history, buyer feedback, dispute rates, and fulfillment metrics — while resisting manipulation and adapting to changing seller behavior over time.
public class SellerTrustScoreEngine
{
public SellerTrustScore CalculateScore(SellerMetrics metrics)
{
double score = 0;
// Transaction volume (20% weight)
score += Normalize(metrics.TotalSales, 0, 100_000) * 0.20;
// Rating (25% weight) — Bayesian average with prior
var bayesianRating = (metrics.AverageRating * metrics.RatingCount
+ 4.0 * 25) / (metrics.RatingCount + 25);
score += (bayesianRating / 5.0) * 0.25;
// Defect rate inverse (20% weight)
score += (1.0 - Normalize(metrics.DefectRate, 0, 0.1)) * 0.20;
// Shipping speed (15% weight)
score += (1.0 - Normalize(metrics.AverageShipDays, 0, 7)) * 0.15;
// Response rate (10% weight)
score += metrics.ResponseRate * 0.10;
// Account age (10% weight) — newer sellers penalized slightly
score += Normalize(metrics.AccountAgeDays, 0, 365) * 0.10;
return new SellerTrustScore
{
SellerId = metrics.SellerId,
Score = Math.Round(score * 100, 2),
Tier = score > 0.8 ? "Platinum" :
score > 0.6 ? "Gold" :
score > 0.4 ? "Silver" : "Bronze",
CalculatedAt = DateTime.UtcNow
};
}
private double Normalize(double value, double min, double max)
{
return Math.Clamp((value - min) / (max - min), 0, 1);
}
}
Trust Score Components
| Signal | Weight | Data Source | Update Frequency |
|---|---|---|---|
| Transaction Volume | 20% | Order database | Daily |
| Buyer Rating | 25% | Review system | Real-time |
| Defect Rate | 20% | Returns + disputes | Daily |
| Shipping Speed | 15% | Carrier tracking | Daily |
| Response Rate | 10% | Messaging system | Hourly |
| Account Age | 10% | Registration date | Static |