Skip to content

Instantly share code, notes, and snippets.

@MrLokans
Created July 1, 2025 15:02
Show Gist options
  • Select an option

  • Save MrLokans/b0ac5c16a1d764f1e0b402e306b4ba01 to your computer and use it in GitHub Desktop.

Select an option

Save MrLokans/b0ac5c16a1d764f1e0b402e306b4ba01 to your computer and use it in GitHub Desktop.
shutdown prompt

Graceful Shutdown Deep Dive Article Generator

Overview

Generate a comprehensive technical article analyzing the graceful shutdown implementation of a specific technology/framework. This prompt creates articles similar to "Anatomy of Graceful Shutdown: Part 4" which deeply examines how complex systems coordinate shutdown across multiple components, processes, and protocols.

Required Inputs

Before starting, you must have:

  1. Target Technology: The main system/framework to analyze (e.g., Celery, Nginx, PostgreSQL, Kafka, etc.)
  2. Local Repository Access: Clone of the technology's source code with specific commit hash
  3. Dependency Stack: Related libraries/components that participate in shutdown (e.g., Celery → Kombu → py-amqp → billiard)
  4. Architecture Understanding: High-level system components and their relationships

Article Structure Template

Part 1: Technology Introduction

  • Hero Introduction: What is this technology and why is its shutdown interesting?
  • Usage Context: Brief API/usage examples showing what gets shut down
  • Complexity Justification: Why shutdown is non-trivial (multiple processes, network protocols, data integrity, etc.)
  • Component Stack: List the technology layers involved with commit hash permalinks

Part 2: Architecture Overview

  • Main Coordinator: The primary component that orchestrates everything (if present)
  • Main Logical Components: All of the moving parts we're actually interested in the context of the shutdown (disk writer, event loops, connections handlers, etc.)
  • Component Relationships: How different parts depend on each other
  • Shutdown Entry Point: Where shutdown signals are received and how they propagate
  • Coordination Mechanism: Blueprint system, dependency injection, event loops, etc.

Part 3: Component-by-Component Analysis

For each major component:

  • Responsibility: What this component manages during shutdown
  • Shutdown Methods: Actual code snippets showing shutdown implementation
  • Resource Cleanup: What resources need careful cleanup
  • Coordination: How it coordinates with other components
  • Timing Considerations: Why order matters for this component

Part 4: Key Insights

  • Design Patterns: What makes this shutdown implementation sophisticated
  • Trade-offs: Choices between speed vs safety, complexity vs reliability
  • Lessons: What other systems can learn from this approach

TODO.md Based Development Process

Use TodoWrite extensively to track your progress through these specific stages:

Research Phase TODOs

  • Clone target repository and identify commit hash for analysis
  • Map out main components and their shutdown-related files
  • Identify signal handling entry points
  • Trace shutdown code paths through dependencies
  • Document component relationships and dependencies

Analysis Phase TODOs

  • Analyze main coordinator/orchestrator component
  • Examine each major component's shutdown implementation
  • Document code snippets with proper GitHub permalinks
  • Identify interesting design patterns and trade-offs

Writing Phase TODOs

  • Draft technology introduction and context
  • Write architecture overview with component relationships
  • Create component-by-component analysis sections
  • Add code references with commit hash permalinks
  • Write insights section highlighting key patterns

Verification Phase TODOs

  • Verify all GitHub links use commit hashes and point to correct lines
  • Test that code snippets are syntactically correct
  • Ensure technical claims match actual implementation
  • Check that article maintains consistent technical depth

Code Reference Standards

GitHub Permalink Format

- [Component shutdown method](https://github.com/owner/repo/blob/COMMIT_HASH/path/to/file.ext#L123-L145)

Requirements:

  • Always use commit hashes, never branch names
  • Include line numbers for specific code references
  • Use line ranges (L123-L145) for multi-line code blocks
  • Verify links are accessible and point to correct code

Code Snippet Integration

**Component shutdown logic** (path/to/file.ext:123-145):
```python
def shutdown_method(self):
    """Actual method from the codebase"""
    # Include real implementation, not pseudo-code
    self.cleanup_resources()
    self.coordinate_with_dependencies()

Multi-Layer Code Tracing

For complex shutdown flows, show the complete call chain:

**1. Signal Handler** (app/signal.py:45):
**2. Main Loop** (core/loop.py:123):  
**3. Component Coordinator** (components/base.py:67):
**4. Individual Component** (components/worker.py:234):

Architecture Documentation Requirements

Component Dependency Mapping

Create clear dependency graphs showing:

  • Which components depend on others
  • Shutdown order requirements (reverse dependency order)
  • Communication mechanisms between components

MermaidJS scripts can be used.

Timing and Coordination Analysis

Explain:

  • Why specific shutdown order matters
  • What happens if components shut down in wrong order
  • How the system prevents race conditions during shutdown
  • Timeout mechanisms and fallback strategies

MermaidJS timing diagrams can be used here.

Language-Agnostic Adaptation Guidelines

For Different Programming Languages

Go: Focus on goroutine coordination, context cancellation, WaitGroups Java: Emphasize shutdown hooks, thread pool lifecycle, resource management
C/C++: Highlight signal handling, memory cleanup, resource deallocation JavaScript/Node.js: Event loop drainage, connection cleanup, graceful server shutdown Rust: Ownership patterns in shutdown, Drop trait implementations, async cleanup

For Different System Types

Web Servers: Request drainage, connection cleanup, graceful listener shutdown Databases: Transaction completion, checkpoint writing, connection termination Message Brokers: Queue draining, client disconnection, cluster coordination
Container Orchestrators: Pod lifecycle, resource cleanup, cluster state updates

Proofreading Framework Integration

After completing the initial draft, systematically apply this proofreading process:

Technical Accuracy Verification TODOs

  • Verify all GitHub links point to correct commit hashes and line numbers
  • Test that code snippets compile/run correctly
  • Cross-reference technical claims with actual source code
  • Ensure implementation details match current codebase state

AI Language Pattern Detection TODOs

  • Remove dramatic phrases ("The Journey Complete", "Shutdown Dance", "Coordination Magic")
  • Eliminate AI transitions ("What emerges is...", "The beauty lies in...", "The elegance of...")
  • Replace overly formal language with direct technical explanations
  • Convert numbered insight lists to natural prose paragraphs
  • Remove formulaic conclusions and artificial wrap-ups
  • Replace cute analogies with straightforward technical explanations

Narrative Flow Assessment TODOs

  • Check logical progression from overview to implementation details
  • Ensure smooth transitions between component analyses
  • Verify each section builds naturally on previous sections
  • Remove redundant explanations of previously covered concepts
  • Maintain consistent technical depth throughout

Grammar and Style Review TODOs

  • Fix grammar errors and typos
  • Remove unnecessary articles ("the Celery" → "Celery")
  • Clean up formatting (empty lines, inconsistent spacing)
  • Ensure consistent terminology and capitalization
  • Verify proper capitalization of technical terms

Consistency Verification TODOs

  • Check consistent naming conventions across the article
  • Verify capitalization consistency for technical terms
  • Ensure component names are used consistently
  • Validate that examples match described patterns
  • Confirm technical terms have consistent definitions

Quality Indicators

Excellent Technical Writing Should:

  • Sound like it was written by a human expert familiar with the codebase
  • Use direct, precise language without unnecessary flourishes
  • Maintain consistent technical terminology throughout
  • Have logical flow from architectural overview to implementation details
  • Include accurate, verifiable code references with proper permalinks
  • Explain complex coordination patterns clearly without oversimplification

Red Flags to Address:

  • Overly dramatic section headers or narrative transitions
  • AI-typical phrases like "emerges", "elegance", "beauty", "sophisticated dance"
  • Technical inaccuracies or references to non-existent code
  • Inconsistent terminology or component naming
  • Missing or broken GitHub permalinks
  • Shallow analysis that doesn't examine actual implementation details

Writing and Presentation Adjustments

Based on practical experience creating these articles, consider these important adjustments:

Technology Introduction Requirements

  • Explain the technology thoroughly before diving into technical details
  • Define technical terms (like TSDB, WAL, etc.) when first introduced
  • Provide concrete context (e.g., "scrapes HTTP endpoints every 15 seconds")
  • Give real-world relevance (e.g., "having data when applications crash at 3 AM")
  • Avoid jargon without explanation, even for common terms in the domain

Code Reference Implementation

  • Use standard markdown code blocks instead of custom shortcodes for maximum compatibility
  • Include descriptive headers for each code block (e.g., "TSDB registration", "Manager.Stop() coordination")
  • Maintain GitHub permalinks in format [description](GitHub-URL)
  • Ensure code renders properly across different markdown renderers
  • Test code block rendering before finalizing the article

Library/Framework Introduction Pattern

When using external libraries (like oklog/run.Group):

  • Introduce the library with its purpose and GitHub link
  • Explain the problem it solves before showing the solution
  • Provide a realistic, manageable example demonstrating the pattern
  • Use complete, runnable code that readers can understand and test
  • Bridge from simple example to complex implementation with clear transitions

Content Flow Improvements

  • Start broad, then narrow - technology overview → architecture → implementation details
  • Use progressive disclosure - introduce concepts before using them in complex contexts
  • Provide practical examples before showing production-scale implementations
  • Maintain consistent technical depth throughout the article
  • Create clear section transitions that guide readers through the analysis

Link Verification Tool

To efficiently verify all links in your articles, use the provided link checker script:

# Check links in specific files
./check_links.sh article.md

# Check all markdown files in current directory
./check_links.sh

# Script features:
# - Uses HEAD requests for efficiency (10s timeout)
# - Handles redirects, rate limiting, and DNS failures
# - Provides colored output with HTTP status codes
# - Retries failed requests automatically
# - Skips localhost URLs to avoid false positives
# - Reports comprehensive statistics

The script efficiently checks HTTP(S) links using curl with proper timeout handling, DNS resolution error management, and status code interpretation (200/301/302 = valid, 404 = broken, 403 = auth required, etc.).

Final Checklist

Before publishing, ensure:

  • Technology is introduced with sufficient context and explanation
  • All technical terms are defined when first used
  • Code blocks use standard markdown format with descriptive headers
  • All links verified using ./check_links.sh [article.md]
  • All GitHub links use commit hashes and point to correct code sections
  • Code snippets are syntactically correct and match source
  • Technical claims are supported by actual implementation
  • Article maintains consistent technical depth throughout
  • Component relationships are clearly explained with diagrams if needed
  • Shutdown coordination mechanisms are thoroughly analyzed
  • Key insights section provides actionable lessons for other systems
  • External libraries are properly introduced with examples
  • Content flows logically from simple concepts to complex implementations
  • Proofreading framework has been systematically applied
  • Writing sounds natural and human, not AI-generated

Example Technology Applications

Web Frameworks

  • Django: Request handling, database connections, middleware shutdown
  • Express.js: Server shutdown, middleware cleanup, connection draining
  • Spring Boot: Bean lifecycle, connection pools, actuator endpoints

Message Systems

  • Apache Kafka: Broker shutdown, consumer group coordination, log segment management
  • RabbitMQ: Connection management, queue persistence, cluster coordination
  • Redis: Memory persistence, client connections, cluster failover

Databases

  • PostgreSQL: Connection termination, WAL flushing, background processes
  • MongoDB: Replica set coordination, connection cleanup, storage engine shutdown
  • MySQL: Storage engine shutdown, connection threads, replication coordination

Container/Orchestration

  • Docker: Container lifecycle, volume cleanup, network teardown
  • Kubernetes: Pod graceful termination, service endpoint updates, volume unmounting
  • Containerd: Runtime coordination, namespace cleanup, shim processes

This prompt ensures you create technically accurate, deeply researched articles that examine real implementation details while maintaining readability and providing actionable insights for software engineers working on similar systems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment