Advance Diploma in Blockchain
Decentralized Applications
•
Advance Diploma
DApp Architecture and Design Patterns
Introduction
A decentralized application (DApp) combines a user-facing application with blockchain-based computation, cryptographic identity, and often a set of off-chain services. Unlike a conventional web application, a DApp cannot assume that a central server is trusted, always available, or able to reverse an error. Its architecture must therefore address determinism, transaction finality, adversarial behavior, key management, upgrade governance, data availability, and cost.
A useful DApp design separates responsibilities among presentation, application, blockchain, data, and integration layers. This separation does not make a system decentralized by itself. Decentralization depends on who controls execution, upgrades, assets, identity, and data. Nevertheless, layered architecture provides a disciplined way to decide what belongs on-chain, what belongs off-chain, and how components interact.
This chapter explains the principal layers of Web3 architecture and examines modularity, proxy, factory, registry, escrow, and multisignature patterns. It also develops a practical design method and applies it to an illustrative decentralized marketplace.
Learning Objectives
By the end of this chapter, a learner should be able to:
Explain the major layers of a DApp architecture.
Distinguish on-chain responsibilities from off-chain responsibilities.
Select appropriate modularity, proxy, factory, registry, escrow, and multisignature patterns.
Analyse security, governance, performance, privacy, and cost trade-offs.
Design a reliable DApp using explicit trust boundaries and failure handling.
Evaluate an architecture against operational and regulatory requirements.
1. The Layered Web3 Architecture
A conventional application commonly places business logic in a server and stores state in a database. A DApp distributes these functions. Smart contracts provide publicly verifiable state transitions, while wallets sign transactions and off-chain components improve usability and handle data that is unsuitable for a blockchain.
Blockchain nodes, RPC endpoints, monitoring, key-management systems
The layers interact through explicit interfaces. A wallet does not merely “log in”; it proves control of an address by signing a message or transaction. An RPC endpoint is not necessarily trustworthy: it may censor requests, return stale data, or impose availability limits. A DApp should therefore offer appropriate fallbacks and verify critical information independently where feasible.
Figure: A layered DApp architecture. Data and control may flow in both directions; arrows show the principal dependency direction.
1.1 Presentation and wallet interaction
The presentation layer should show the connected network, account, transaction parameters, estimated fees, and meaningful confirmation states. It should never ask users to approve an opaque transaction merely because a button says “continue.” Addresses should be displayed with checksums or human-readable names where supported. The interface must also distinguish a submitted transaction from a confirmed transaction.
1.2 Application and integration services
Application services can query indexed blockchain data, prepare transactions, calculate quotes, send notifications, and operate relayers. They may improve usability but should not silently become the sole authority for balances or ownership. If an application server can alter protocol outcomes without an on-chain check, the system has a central trust dependency.
1.3 Protocol layer
Smart contracts enforce rules such as ownership, payment, collateral, voting, and settlement. Contract execution is deterministic: identical valid inputs and state produce the same result on a given chain. Contracts should be small enough to audit, explicit about authority, and designed around failure rather than assuming every call succeeds.
1.4 Data and indexing layer
Blockchains are strong at integrity and weak at low-cost, high-volume querying. Events allow indexers to build searchable views, but events are not automatically contract state and should not replace data required for future authorization or settlement. Large documents, images, and private records normally belong in decentralized storage or controlled off-chain systems, with content identifiers or hashes anchored on-chain.
1.5 Infrastructure layer
Infrastructure includes nodes, RPC providers, chain bridges, deployment systems, monitoring, and signing environments. A DApp may be protocol-decentralized while relying operationally on one RPC provider or one cloud region. This distinction should be documented in the threat model.
2. Establishing the On-Chain/Off-Chain Boundary
The central architectural decision is which facts must be independently verifiable and which processes can be delegated. A fact generally belongs on-chain when it determines ownership, payment, permissions, collateral, settlement, or a state transition that participants must be able to verify without trusting one operator. Data generally belongs off-chain when it is large, private, rapidly changing, computationally expensive, or legally required to be erasable.
On-chain is usually appropriate for
Off-chain is usually appropriate for
Asset ownership and balances
Images, documents, and rich media
Settlement and escrow conditions
Search indexes and recommendations
Access-control decisions
Personal data and confidential business records
Governance results
Notifications and user preferences
Hashes, commitments, and content identifiers
Machine-learning inference and analytics
This is not a binary choice. A document can be stored off-chain while its content hash and version identifier are recorded on-chain. An oracle can deliver an external price, but the contract must specify the accepted source, update conditions, and consequences of stale data.
Decision criteria
A boundary decision should answer five questions:
Verification: Must an independent participant verify this fact?
Finality: Must the fact be resistant to unilateral alteration?
Privacy: Would public replication expose protected information?
Cost and scale: Can the chain process the volume economically?
Recovery: What happens if the off-chain service disappears or gives an incorrect result?
A useful principle is to minimize trusted computation, not necessarily all off-chain computation. Off-chain work is acceptable when its result can be checked, challenged, reproduced, or safely treated as advisory.
3. Modularity as a Reliability Strategy
Modularity divides a protocol into components with clear responsibilities and interfaces. Examples include an access-control module, payment module, fee module, treasury module, oracle adapter, and settlement module. Modularity reduces cognitive load and permits targeted testing, but excessive fragmentation can create dangerous cross-contract assumptions.
A good module has:
a narrow purpose;
explicit inputs, outputs, and invariants;
documented caller permissions;
predictable failure behavior;
tests for both success and rejection paths;
minimal state duplication.
An invariant is a property that must remain true after every valid state transition. For an escrow, an example is that released funds cannot exceed the deposited amount. For a token, total balances should remain consistent with minting and burning rules. Invariants should be tested through unit tests, integration tests, fuzzing, and, where justified, formal verification.
Interfaces are especially important in Solidity-like environments. A contract should interact with another contract through a defined interface rather than assuming undocumented storage layout or behavior. External calls should account for reentrancy, return-value irregularities, gas limits, and malicious implementations.
4. Core Design Patterns
4.1 Proxy pattern
A proxy delegates calls to an implementation contract while retaining the address and storage used by users. The proxy can therefore preserve a stable public address while logic changes through an upgrade procedure.
Common models include:
Transparent proxy: administrative calls are separated from ordinary user calls.
UUPS proxy: upgrade logic is implemented in the implementation contract, usually reducing proxy complexity but increasing implementation responsibility.
Beacon proxy: multiple proxies obtain their implementation from a shared beacon.
The main risk is that upgradeability changes immutability into governance. An upgrade administrator, compromised key, or malicious implementation may alter balances, permissions, or withdrawal logic. Storage-layout compatibility is also essential: inserting or reordering variables incorrectly can corrupt state. Upgrade controls should therefore use multisignature approval, timelocks, event logging, emergency procedures, and independent review.
A proxy is unsuitable when users require absolute code immutability or when upgrade authority cannot be governed credibly. An immutable core with replaceable peripheral modules may provide a better compromise.
4.2 Factory pattern
A factory creates standardized instances, such as escrow agreements, lending pools, or token collections. It can validate parameters, register the new address, emit creation events, and establish consistent initialization.
A factory improves discoverability and reduces deployment errors. However, a factory is not automatically safe: if it allows arbitrary implementations, attackers may create deceptive or incompatible instances. The factory should define approved implementations, initialization rules, creator permissions, and version information. Deterministic deployment may allow an address to be calculated before deployment, but address prediction must account for the deployment scheme and initialization data.
4.3 Registry pattern
A registry maps identifiers to addresses or metadata, for example:
approved token addresses;
supported collateral types;
factory versions;
dispute resolvers;
contract modules.
Registries simplify integration but become critical infrastructure. A compromised registry can redirect users to malicious contracts. Governance should define who can add, replace, or remove entries, whether changes are delayed, and how clients verify registry authenticity. Historical versions should remain auditable rather than being silently overwritten.
4.4 Escrow pattern
An escrow holds assets until a specified condition is satisfied. Participants may be a payer, recipient, and arbiter. A robust escrow specifies deposit, release, refund, dispute, timeout, and emergency paths.
The contract should enforce that:
only authorized parties can initiate each transition;
funds cannot be released twice;
a dispute cannot be bypassed by an ordinary release call;
deadlines use a clearly stated time source and tolerance;
token transfer failures are handled;
reentrancy cannot cause repeated withdrawal.
A state machine is preferable to scattered Boolean variables. For example:
Created → Funded → Released
Funded → Disputed → Released or Refunded
Funded → TimedOut → Refunded
The timeout must be a fallback, not an accidental method of seizing funds. Real-world disputes may also involve legal identity, evidence, and jurisdiction; code alone cannot resolve every contractual question.
4.5 Multisignature pattern
A multisignature wallet requires several authorized signers to approve an operation. In an m-of-n design, at least m distinct valid signatures are required from n authorized signers. For example, a 3-of-5 wallet requires three of five signers.
Multisignature control reduces dependence on one key but introduces coordination, signer loss, collusion, and operational risks. Signers should be independent, use hardware-backed custody where appropriate, and follow transaction-verification procedures. Rotation, recovery, quorum changes, and emergency actions must be specified before deployment.
A multisignature wallet is often used for upgrade administration, treasury withdrawals, registry changes, and pause controls. It is not a substitute for least privilege: the wallet should possess only the authority necessary for its role.
5. A Systematic DApp Design Method
Step 1: Identify actors and assets
List users, administrators, arbitrators, service providers, contracts, tokens, documents, and credentials. For each actor, state what they can do and what they must not do.
Step 2: Define trust assumptions
Record assumptions such as “the price oracle is honest within a stated bound,” “the RPC endpoint is unavailable but not authoritative,” or “a quorum of governance signers will not collude.” An undocumented assumption is a hidden vulnerability.
Step 3: Specify states and transitions
Write a state machine before writing contract code. Each transition should identify caller, preconditions, state changes, external calls, emitted events, and failure behavior.
Step 4: Place data deliberately
For every data item, record its location, integrity mechanism, privacy classification, retention requirement, and recovery method. Avoid storing personal data on an irreversible public ledger merely because storage is technically possible.
Step 5: Choose patterns conservatively
Use a proxy only when the benefits of controlled upgrades exceed the governance risk. Use a factory when repeated instances require standardization. Use a registry when shared discovery is necessary. Use escrow when conditional settlement is central. Use multisignature control for high-impact administration.
Step 6: Threat-model the composition
Patterns can interact badly. A registry-controlled proxy factory may allow one governance error to affect every deployed instance. An escrow calling an untrusted token may face reentrancy or non-standard transfer behavior. Review the complete call graph, not isolated contracts.
Step 7: Test and operate
Testing should include normal flows, invalid callers, boundary times, zero values, repeated calls, failed external calls, malicious tokens, upgrade simulations, and chain reorganization assumptions. Production requires monitoring of events, balances, failed transactions, abnormal administrative actions, and oracle freshness.
6. Illustrative Case: A Decentralized Equipment Marketplace
The following is a fictional illustrative case.
Background and problem
A cooperative rents specialist equipment to members. It wants transparent deposits and settlement but must keep equipment photographs, inspection reports, and personal identification private. Members also need a dispute process when equipment is damaged.
Analysis
The deposit and settlement rules require independent verification. Inspection photographs are large and may contain personal information. The cooperative must update fee parameters occasionally, but no single officer should control funds or alter contracts instantly.
Architecture and solution
The marketplace uses:
A web interface and wallet connection for listings, booking, deposit, and status display.
A registry containing the approved escrow implementation and supported payment token.
A factory that creates one escrow instance per booking.
An escrow contract holding the deposit and recording booking status, deadlines, parties, and document hashes.
Decentralized storage for encrypted inspection reports, with their content identifiers committed to the escrow.
A multisignature wallet for registry changes, emergency pauses, and fee administration.
An indexer that reads events for search and reporting; the contract remains authoritative for ownership and settlement.
A timelocked proxy upgrade process for non-immutable modules, with a documented emergency pause.
The escrow state machine is:
Created → Funded → Completed → Released
or
Funded → Disputed → Released or Refunded.
A timeout permits refund only after the stated deadline and only when no dispute is active. The contract uses pull-based withdrawals: after a release decision, a beneficiary withdraws their recorded amount rather than receiving funds through a complex chain of nested calls.
Outcome
The design makes deposits and settlement auditable while limiting public exposure of personal information. It also makes governance visible: users can inspect the multisignature signers, timelock, implementation address, and registry history. Its remaining risks include compromised signers, incorrect inspection evidence, storage unavailability, token integration defects, and the legal enforceability of automated dispute outcomes.
Learning points
The case demonstrates that decentralization is a spectrum. The settlement rule is strongly decentralized, while indexing and storage are service layers with separate availability and privacy controls. Patterns are useful only when their authority and failure modes are explicit.
7. Security, Governance, and Regulation
Security begins with authorization. Every privileged function should use least privilege, explicit role separation, and event logging. Checks-effects-interactions ordering, reentrancy defenses, safe token-handling libraries, pausability, and bounded administrative operations are common safeguards, but none replaces review of business logic.
Governance must address who can upgrade code, change a registry, pause withdrawals, add signers, alter fees, or resolve disputes. A transparent governance process should disclose proposal content, voting or signing thresholds, delays, implementation addresses, and emergency powers. Timelocks provide observation time but do not make a malicious decision safe.
Privacy requires special care because public blockchains are transparent and often permanent. Wallet addresses may become linkable through transaction patterns. Encryption protects content but not necessarily metadata, and key loss can make encrypted records unrecoverable. Data-minimization and lawful retention policies should be designed before deployment.
Regulatory classification varies by jurisdiction. A token, escrow service, exchange, custody arrangement, or identity process may trigger licensing, consumer-protection, sanctions-screening, tax, or data-protection obligations. Technical decentralization does not automatically remove legal responsibility. Professional deployments require legal review, incident procedures, user disclosures, and audit trails.
8. Contemporary Developments and Best Practices
Account abstraction and smart-contract wallets can improve recovery, spending limits, batching, and sponsored transactions, but they introduce new validation and paymaster trust assumptions. Layer-2 networks reduce transaction cost and increase throughput, while bridges add significant cross-domain risk. Modular blockchain stacks can separate execution, consensus, and data availability, but developers must understand the security assumptions of each layer.
AI may help classify support requests, detect anomalous transactions, or summarize governance proposals. It should not silently determine irreversible settlement or access-control decisions without an auditable rule, human oversight where appropriate, and protection against manipulated inputs.
Recommended practices include:
keep the immutable core as small as practical;
document every privileged role and trust assumption;
use interfaces and versioned schemas;
emit events for meaningful state transitions;
treat indexers as views, not authorities;
use multisignature control and timelocks for high-impact administration;
test adversarial and recovery paths;
publish upgrade, pause, and incident procedures;
minimize personal data on-chain;
monitor both technical and governance events;
conduct independent security review before handling valuable assets.
Chapter Summary
DApp architecture distributes responsibilities across presentation, application, protocol, data, and infrastructure layers. The on-chain/off-chain boundary should be decided by verification, finality, privacy, cost, scale, and recovery requirements. Modularity improves maintainability when interfaces and invariants are explicit.
Proxy, factory, registry, escrow, and multisignature patterns solve different problems. Proxies support controlled upgrades but create governance and storage-layout risks. Factories standardize repeated deployments. Registries improve discovery but become critical trust points. Escrows implement conditional settlement through explicit state machines. Multisignature wallets reduce single-key risk but require robust signer governance.
Reliable DApps are designed through actor analysis, trust assumptions, state modelling, threat analysis, testing, monitoring, and operational governance. Decentralization is not an architectural label; it is an evidence-based description of who controls computation, assets, upgrades, data, and recovery.
Key Terms
DApp: An application that combines user interfaces with blockchain-based protocols and services.
Layered architecture: Organization of a system into components with distinct responsibilities and interfaces.
Smart contract: Deterministic code deployed on a blockchain that changes state according to defined rules.
On-chain: Data or computation recorded or executed on a blockchain.
Off-chain: Data or computation performed outside the blockchain’s replicated execution environment.
Oracle: A mechanism that supplies external information to a blockchain protocol.
Modularity: Division of a system into cohesive components with controlled dependencies.
Invariant: A property that must remain true after every valid state transition.
Proxy: A contract that delegates calls to an implementation while preserving a stable address or storage context.
Upgradeability: The capability to change contract logic under defined authority and procedures.
Factory: A contract or service that creates standardized contract instances.
Registry: An authoritative or governed mapping between identifiers, addresses, and metadata.
Escrow: A mechanism that holds assets until specified release, refund, or dispute conditions occur.
Multisignature: Authorization requiring approvals from multiple independent signers.
Timelock: A delay between approval of an administrative action and its execution.
Reentrancy: An exploit in which external control returns to a contract before an earlier operation is complete.
Indexer: A service that organizes blockchain events and state for efficient querying.
Trust boundary: A point at which assumptions about authority, integrity, privacy, or availability change.
Review Questions
Short Answer Questions
What are the five principal layers of a practical DApp architecture?
Give two examples of information that is usually better stored off-chain.
What is the main governance risk introduced by a proxy contract?
What purpose does a factory serve in a smart-contract system?
Why should an escrow be designed as an explicit state machine?
Long Answer Questions
Explain how a DApp’s presentation, protocol, data, and infrastructure layers interact. Include the role and limitations of RPC providers and indexers.
Compare proxy, factory, and registry patterns, including their benefits, risks, and appropriate governance controls.
Describe a complete on-chain/off-chain decision framework for a DApp handling payments, documents, and personal information.
Explain how multisignature wallets and timelocks improve governance while introducing operational risks.
Design the states, transitions, roles, and failure paths for a decentralized escrow application.
Analytical / Application Questions
A protocol uses one upgradeable proxy, one registry, and a single administrator key. Analyse the systemic risks and propose a safer governance architecture.
Design an architecture for a decentralized insurance application. Identify which data must be on-chain, which can remain off-chain, and how oracle failure should be handled.
A marketplace’s indexer reports that a user owns an asset, but the blockchain state shows a different owner. Explain which source should control settlement and how the application should recover operationally.
Multiple Choice Questions with Answers
Question 1
Which layer normally contains smart contracts and token rules?
A. Presentation layer
B. Application layer
C. Protocol layer
D. Infrastructure layer
Correct Answer: C. Protocol layer
Question 2
Which item is generally most suitable for on-chain storage?
A. A high-resolution product video
B. A private medical record
C. A settlement condition that determines payment
D. A search-result ranking
Correct Answer: C. A settlement condition that determines payment
Question 3
What is a principal risk of an upgradeable proxy?
A. It cannot preserve a contract address
B. A compromised upgrade authority may change protocol behavior
C. It prevents all event emission
D. It eliminates the need for testing
Correct Answer: B. A compromised upgrade authority may change protocol behavior
Question 4
What is the main purpose of a factory pattern?
A. To create standardized contract instances
B. To encrypt every blockchain transaction
C. To replace all governance mechanisms
D. To provide internet connectivity
Correct Answer: A. To create standardized contract instances
Question 5
Which statement best describes a registry?
A. A mapping of approved identifiers, addresses, or metadata
B. A private key recovery phrase
C. A temporary transaction queue only
D. A consensus algorithm
Correct Answer: A. A mapping of approved identifiers, addresses, or metadata
Question 6
In a multisignature wallet, what does a 3-of-5 rule mean?
A. Three wallets may be created from five tokens
B. Five signatures are required from three signers
C. At least three of five authorized signers must approve
D. Three transactions must be mined in five blocks
Correct Answer: C. At least three of five authorized signers must approve
Question 7
Why are explicit escrow states preferable to scattered Boolean flags?
A. They make all transactions free
B. They clarify permitted transitions and prevent contradictory states
C. They remove the need for authorization
D. They guarantee correct external evidence
Correct Answer: B. They clarify permitted transitions and prevent contradictory states
Question 8
Which statement about an indexer is correct?
A. It should automatically override blockchain state
B. It is a query service and should not silently become the settlement authority
C. It replaces smart-contract authorization
D. It makes private data permanently confidential
Correct Answer: B. It is a query service and should not silently become the settlement authority
Question 9
Which control provides observation time before an approved administrative action executes?
A. Timelock
B. Factory
C. Event indexer
D. Content hash
Correct Answer: A. Timelock
Question 10
Which is the best general principle for placing data on-chain?
A. Place all data on-chain because blockchains are databases
B. Place data on-chain when independent verification and durable state are important
C. Place personal data on-chain to simplify privacy compliance
D. Place only images on-chain
Correct Answer: B. Place data on-chain when independent verification and durable state are important