Chapter 20 Exercises: Event-Driven Architecture with COBOL


Section A: Conceptual Understanding (Exercises 1–8)

Exercise 1: Request/Reply vs. Event-Driven Analysis

For each of the following CNB message flows, determine whether it should use request/reply or event-driven (pub/sub) architecture. Justify your choice with specific technical reasoning.

a) ATM cash withdrawal authorization — the ATM must receive approve/deny before dispensing cash.

b) Wire transfer submission — fraud, compliance, AML, audit, and customer notification all need the transaction data.

c) Real-time balance inquiry from the mobile banking app.

d) End-of-day account statement generation — the statement rendering system, the email notification system, and the archive system all need the statement data.

e) Credit score lookup from an external bureau during loan origination.

f) Customer address change — core banking, card management, lending, and marketing all maintain customer addresses.

g) FedNow instant payment settlement — the Federal Reserve requires a response within 20 seconds.


Exercise 2: Trigger Type Selection

For each queue scenario, select the appropriate trigger type (FIRST, EVERY, or DEPTH) and explain your reasoning. Identify the risk if the wrong trigger type is chosen.

a) A queue that receives 50,000 ACH transaction messages when an ACH file is processed, with 2–3 file arrivals per day and long idle periods between them.

b) A queue that receives critical regulatory alerts — approximately 5 per day — each requiring immediate independent processing.

c) A queue that accumulates customer notification requests throughout the day. The notification system should batch them in groups of 500 for efficient processing.

d) A queue that receives real-time market data updates — approximately 10,000 messages per second during trading hours.

e) A queue that receives incoming wire transfer requests — approximately 200 per hour, evenly distributed.


Exercise 3: CICS Event Processing Decision Matrix

For each scenario, determine whether CICS EP (event binding) or application-level MQPUT is the better approach for event emission. Consider: code change risk, transactional consistency, deployment speed, and long-term maintainability.

a) Adding fraud detection events to a 15-year-old wire transfer program that processes $4.7 billion per day.

b) Building a new loan origination system from scratch where event emission is a day-one requirement.

c) Capturing audit events from 200 CICS transactions for a new regulatory reporting system, with a 90-day implementation deadline.

d) Emitting events that must be transactionally consistent with DB2 updates (the event must not exist if the transaction rolled back).

e) Capturing events from a third-party vendor COBOL program where you don't have source code access.


Exercise 4: Topic Hierarchy Design

Design a topic hierarchy for Pinnacle Health Insurance's claims processing system. The system produces the following events: - Claim submitted (by channel: online portal, paper, EDI) - Claim acknowledged - Claim assigned to adjudicator - Claim adjudicated (approved, denied, pending additional info) - Payment issued - Explanation of Benefits (EOB) generated - Claim appealed - Appeal decided

Your topic hierarchy should: - Support wildcard subscriptions for common access patterns - Follow a consistent naming convention - Not create topic explosion (no per-adjudicator or per-member topics) - Include comments explaining the design rationale


Exercise 5: Event Schema Design

Design a COBOL copybook for a "Claim Adjudicated" event for Pinnacle Health's claims system. Include: - A standard event header (type, version, ID, timestamp, source, correlation ID) - FILLER fields for forward compatibility (20% of total record length) - Payload fields appropriate for claim adjudication (claim number, member ID, provider ID, adjudication result, allowed amount, paid amount, reason codes) - Comments documenting each field's purpose and valid values


Exercise 6: Saga Design

Design a saga for the following business process at Federal Benefits Administration: A beneficiary submits a change of address, which must update four systems: the master beneficiary record (IMS), the payment mailing address (DB2), the healthcare enrollment system (external, via MQ), and the document management system (external, via HTTP API).

For each step: a) Define the forward action (what happens when the step succeeds) b) Define the compensating action (what happens when a later step fails and this step must be undone) c) Identify whether the step is retriable or not d) Determine the saga's overall consistency model (strong or eventual)


Exercise 7: Idempotency Analysis

For each event consumer scenario, describe the specific harm caused by processing a duplicate event, and design the idempotency mechanism to prevent it.

a) A consumer that debits a customer account when a "Fee Charged" event is received.

b) A consumer that sends an email notification when a "Wire Transfer Completed" event is received.

c) A consumer that increments a counter in a statistics table when a "Login Successful" event is received.

d) A consumer that inserts a row in an audit log table when any event is received.


Exercise 8: Anti-Pattern Identification

Read the following scenario and identify all event-driven anti-patterns present. For each anti-pattern, explain the risk and propose a fix.

"Our new system publishes a TRANSACTION_COMPLETE event with 187 fields (all data from the transaction, the customer profile, the account details, and the branch information) to a topic structure where each branch has its own topic (EVENTS/BRANCH/001/COMPLETE, EVENTS/BRANCH/002/COMPLETE, ..., up to 3,200 branches). The event is published without MQPMO-SYNCPOINT because we need maximum throughput. We have 14 consumers, and we rely on MQ's ordering guarantee to ensure consumers process events in the correct sequence. None of the subscription queues have depth monitoring because MQ is reliable and queues don't fill up."


Section B: Technical Implementation (Exercises 9–17)

Exercise 9: Triggered Program Implementation

Write a complete COBOL CICS program that is triggered by MQ. The program should:

  1. Retrieve the trigger message using EXEC CICS RETRIEVE
  2. Extract the queue name from the trigger message
  3. Open the triggered queue for input
  4. Process all available messages in a loop (MQGET with wait interval = 5 seconds)
  5. For each message: parse a wire transfer event, validate the amount (reject transfers over $10 million), and write accepted transfers to a DB2 table
  6. Handle all error conditions (RETRIEVE failure, MQOPEN failure, MQGET failure, DB2 errors)
  7. Log processing statistics (messages processed, accepted, rejected) to CICS TD queue
  8. Close the queue and return

Include the complete WORKING-STORAGE SECTION with all copybooks and data definitions.


Exercise 10: MQ Trigger Configuration

Write the complete MQSC definitions for the following triggered processing setup:

  • Application queue: PH.CLAIMS.SUBMITTED — receives claim submission events
  • Trigger type: FIRST (claims arrive in bursts during business hours)
  • Process definition: starts CICS transaction CLMP
  • Initiation queue: SYSTEM.CICS.INITIATION.QUEUE
  • Backout threshold: 5, with backout queue PH.CLAIMS.BACKOUT
  • Maximum message length: 16KB
  • Maximum queue depth: 500,000
  • Messages are persistent

Also define the backout queue with appropriate attributes.


Exercise 11: CICS Event Binding Configuration

Write a complete CICS event binding XML document that captures account closure events from CNB's account management program (ACCTMGR1). The event should be captured when the program executes EXEC CICS DELETE FILE('ACCTMSTR'). The event should include: - Account number (offset 0, length 16) - Account type (offset 16, length 4) - Closure reason code (offset 20, length 3) - Last balance (offset 23, length 8) - Customer ID (offset 31, length 12)

Deliver the event to MQ queue CNB.EVENTS.ACCOUNT.CLOSED on queue manager HAQM01 in JSON format.


Exercise 12: Pub/Sub Topic and Subscription Configuration

Write the complete MQSC definitions for CNB's wire transfer event pub/sub infrastructure:

a) Define the topic objects for: SUBMITTED, APPROVED, REJECTED, and COMPLETED wire transfer events under a CNB/EVENTS/WIRE/ hierarchy.

b) Define durable administrative subscriptions for: - Fraud system: subscribes to SUBMITTED events only, delivers to FRAUD.WIRE.INBOUND - Compliance system: subscribes to all wire events (wildcard), delivers to COMPL.WIRE.INBOUND - Audit system: subscribes to APPROVED and COMPLETED events, delivers to AUDIT.WIRE.INBOUND - Customer notification: subscribes to COMPLETED and REJECTED events, delivers to NOTIFY.WIRE.INBOUND

c) For each subscription, specify appropriate attributes (durable, expiry, etc.)


Exercise 13: Publishing Events from COBOL

Write the COBOL code (PROCEDURE DIVISION paragraphs only) for publishing a JSON-formatted wire transfer event to the CNB/EVENTS/WIRE/SUBMITTED topic. The code should:

  1. Build the JSON event string from WORKING-STORAGE fields (use STRING verb)
  2. Set up the MQOD for topic publishing (MQOT-TOPIC, topic string)
  3. Open the topic for output
  4. Set MQMD fields (persistence, format, correlation ID)
  5. Publish the event under syncpoint (MQPMO-SYNCPOINT)
  6. Handle all error conditions
  7. Close the topic handle

Exercise 14: Idempotent Event Consumer

Write a complete COBOL paragraph that implements idempotent event processing using a DB2 event log table. The paragraph should:

  1. Extract the event ID from the event header
  2. Check the DB2 event log table for the event ID
  3. If found: increment a duplicate counter and skip processing
  4. If not found: process the event (call a business logic paragraph) and insert the event ID into the log table — all within the same unit of work
  5. Handle DB2 errors appropriately (including deadlock retry)

Define the DB2 table DDL and the COBOL host variable declarations.


Exercise 15: Saga State Machine

Write COBOL code for a saga coordinator that manages a three-step wire transfer saga:

Step 1: Debit source account (DB2 update) Step 2: Submit to correspondent bank (MQPUT to external gateway queue) Step 3: Credit destination account (DB2 update, triggered by reply from correspondent)

The coordinator should: 1. Maintain saga state in a DB2 table 2. Execute each step with appropriate error handling 3. If any step fails, execute compensating actions for all previously completed steps (in reverse order) 4. Log the saga outcome (completed or compensated) for audit

Include the DB2 table DDL for the saga state table.


Exercise 16: Circuit Breaker Implementation

Write a COBOL circuit breaker module that can be called by any event consumer program. The module should:

  1. Accept a service name and success/failure indicator as input
  2. Maintain per-service failure counts and circuit state in WORKING-STORAGE
  3. Implement three states: CLOSED (normal), OPEN (failing, stop processing), HALF-OPEN (testing)
  4. Open the circuit after 10 consecutive failures
  5. Attempt a single probe after a 5-minute cooldown period
  6. Return the circuit state to the caller so it can decide whether to process

Exercise 17: Event Schema Version Handling

Write a COBOL consumer program paragraph that handles three versions of the wire transfer event schema: - Version 1: Basic fields (account from/to, amount, currency) - Version 2: Adds risk score, originator IP, and channel - Version 3: Adds sanctions check result, PEP (Politically Exposed Person) flag, and regulatory classification

The paragraph should: 1. Read the event version from the header 2. Parse version-appropriate fields 3. Log a warning for unknown versions but not abend 4. Populate a normalized working-storage structure regardless of version (using defaults for missing fields)


Section C: Architecture and Design (Exercises 18–25)

Exercise 18: Event-Driven Architecture Assessment

You are the architect for SecureFirst Retail Bank. Yuki Nakamura has asked you to evaluate converting their mobile banking notification system from request/reply to event-driven. Currently, the core banking CICS transaction sends individual MQ request/reply messages to the notification system for each customer action (login, transfer, payment, balance alert).

Write a 1-page architecture assessment covering: a) Current pain points with the request/reply approach b) Proposed event-driven architecture (topic hierarchy, subscriptions, consumer design) c) Migration strategy (how to switch without downtime) d) Risk analysis (what could go wrong, how to mitigate) e) Expected benefits with specific metrics


Exercise 19: Event-Driven Fraud Detection Design

Design the complete event-driven fraud detection architecture for CNB's wire transfer system. Your design should include:

a) Event flow diagram: from wire transfer submission through fraud scoring to alert generation b) MQ trigger configuration for the fraud scoring program c) Event schema for fraud alerts (what data does the alert contain?) d) Pub/sub design for fraud alert distribution (who subscribes to fraud alerts?) e) SLA analysis: can the end-to-end flow meet a 500ms target? f) Failure mode analysis: what happens when each component fails?


Exercise 20: CICS EP vs. Application Events Decision Framework

Create a decision framework (flowchart or decision table) that helps architects choose between CICS Event Processing and application-level event emission. The framework should consider: - Application modification risk - Transactional consistency requirements - Event payload complexity - Development timeline - Long-term maintainability - Testing and debugging ease - Performance overhead

Test the framework against three scenarios from the chapter.


Exercise 21: Event Sourcing Feasibility Study

Federal Benefits Administration (Sandra Chen) is considering event sourcing for the beneficiary master record. The record currently has 450 fields, receives approximately 2 million updates per month, and must support point-in-time reconstruction for audit purposes going back 7 years.

Write a feasibility analysis: a) Calculate the event storage requirements (approximate event size, volume over 7 years) b) Estimate the reconstruction time for a single beneficiary record (assuming average 200 events per beneficiary) c) Design a snapshotting strategy to bound reconstruction time d) Identify the COBOL implementation challenges (copybook evolution, event versioning) e) Recommend: go or no-go, with specific justification


Exercise 22: Saga Pattern for Claims Processing

Design a saga for Pinnacle Health's claims adjudication process:

Step 1: Validate claim data (local) Step 2: Verify member eligibility (external system via MQ) Step 3: Check provider network status (external system via MQ) Step 4: Apply adjudication rules (local, DB2) Step 5: Issue payment (external payment system via MQ) Step 6: Generate EOB (local, batch queue) Step 7: Send member notification (MQ pub/sub)

For each step, define: forward action, compensating action, timeout, and retry policy. Design the saga state machine. Identify which steps can run in parallel.


Exercise 23: Cross-LPAR Event Distribution

CNB runs four LPARs in a Parallel Sysplex. Design the MQ pub/sub infrastructure to distribute events across all four LPARs, ensuring: - Events published on any LPAR are visible to subscribers on all LPARs - Subscriber failure on one LPAR doesn't affect delivery on other LPARs - No single point of failure in the event distribution path - Monitoring can detect event delivery delays across LPARs

Include: queue manager topology, topic host routing, inter-LPAR channel configuration, and monitoring strategy.


Exercise 24: Event-Driven Batch Triggering

Sandra Chen at Federal Benefits Administration wants to replace the agency's 15-minute polling cycle for incoming state enrollment files with event-driven batch triggering. Design the solution:

a) MQ trigger configuration for the enrollment processing batch job b) Process definition that starts a batch job (not a CICS transaction) c) The triggered batch program's structure (how it discovers the queue from the trigger message) d) Error handling: what happens if the batch job abends? How do unprocessed messages get reprocessed? e) Monitoring: how does operations know the triggering is working?


Exercise 25: Complete Event-Driven Architecture Review

You are presenting an event-driven architecture proposal to CNB's architecture review board (Kwame Mensah is the chair). The proposal converts the five highest-volume request/reply flows to event-driven pub/sub.

Prepare a presentation outline covering: a) Current state analysis (flows, volumes, pain points) b) Proposed architecture (topic hierarchy, event schemas, consumer designs) c) Migration strategy (phased, with rollback plan) d) Capacity analysis (topic fan-out overhead, subscription queue sizing) e) Operational model (monitoring, alerting, DLQ processing, on-call runbook) f) Risk register (top 5 risks with mitigations) g) Success metrics (how will you know it's working?)

Kwame will ask three questions. Predict what they are and prepare answers.