Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Tornado

Learn Tornado - 9 Code Examples & CST Typing Practice Test

Tornado is a Python web framework and asynchronous networking library, designed for handling thousands of simultaneous connections. It excels at real-time web services and long-lived network connections.

View all 9 Tornado code examples →
Tornado Simple Counter APITornado Hello World APITornado JSON EchoTornado Query Parameter ExampleTornado Route Parameter ExampleTornado Middleware LoggingTornado Async Delay ExampleTornado 404 ExampleTornado Combined Routes Example

Learn TORNADO with Real Code Examples

Updated Nov 25, 2025

Explain

Tornado uses a non-blocking, single-threaded event loop for handling concurrent connections efficiently.

It combines a web framework with a scalable networking library, suitable for real-time apps.

Supports WebSockets, long polling, and streaming responses natively.

Provides asynchronous request handling using Python's `asyncio` or Tornado's own I/O loop.

Commonly used for chat applications, live dashboards, and APIs requiring high concurrency.

Core Features

RequestHandler classes for defining endpoints

Async I/O via `async def` or `gen.coroutine`

Built-in support for WebSockets

Streaming responses and long-lived connections

Routing via `tornado.web.Application`

Basic Concepts Overview

IOLoop - core event loop

Application - main server object

RequestHandler - class to handle HTTP requests

WebSocketHandler - class for WebSocket connections

Async coroutines - for non-blocking operations

Project Structure

app.py - main server file

handlers/ - RequestHandler classes

templates/ - HTML templates if used

static/ - static files (CSS, JS, images)

utils/ - helper modules and services

Building Workflow

Import Tornado modules (`tornado.web`, `tornado.ioloop`)

Define RequestHandler classes for endpoints

Create Application instance with route mappings

Start IOLoop with `app.listen(port)` and `IOLoop.current().start()`

Use `async def` or `@gen.coroutine` for async operations

Difficulty Use Cases

Beginner: single GET endpoint

Intermediate: CRUD API with async DB calls

Advanced: WebSocket server

Expert: high-concurrency microservices

Auditor: optimize event loop performance

Comparisons

Tornado vs Flask: Tornado supports async and WebSockets, Flask is WSGI-based

Tornado vs Django: Tornado is async and lightweight, Django is feature-rich

Tornado vs FastAPI: Both async, Tornado includes low-level I/O, FastAPI uses Starlette for async web

Tornado vs Node.js frameworks: Tornado is Python-based, async event-loop similar to Node.js

Tornado vs Koa.js: Koa is Node.js minimal async, Tornado is Python async with networking library

Versioning Timeline

2009 - Tornado initial release by FriendFeed team

2010 - Open-sourced and adopted by Facebook

2012-2015 - Async features and WebSocket support improved

2016-2019 - Python 3 support and asyncio integration

2020-2025 - Continuous maintenance and minor optimizations

Glossary

IOLoop - core event loop

RequestHandler - handles HTTP requests

WebSocketHandler - handles WebSocket connections

Application - server object with routes

Coroutine - async function for non-blocking I/O

Installation Setup

Install Python 3.8+

Install Tornado via `pip install tornado`

Create main application file (e.g., `app.py`)

Define request handlers and routes

Run server with `python app.py`

Environment Setup

Install Python 3.8+

Set up virtual environment

Install Tornado via pip

Configure development tools and logging

Verify server runs locally

Config Files

requirements.txt - dependencies

app.py - main server file

handlers/ - request handlers

templates/ - HTML templates

static/ - static files

Cli Commands

pip install tornado -> install Tornado

python app.py -> run server

pip install -r requirements.txt -> install dependencies

pytest -> run tests

docker build/run -> containerize app

Internationalization

No built-in i18n, but can integrate libraries

Supports UTF-8

Serve locale-specific content via custom handlers

Used globally for multilingual applications

Flexible to implement custom translation pipelines

Accessibility

Framework-agnostic

Supports CORS

Accessible via HTTP clients

Runs on all Python-supported platforms

Middleware and handlers enforce security

Ui Styling

Not handled - backend framework

Serve static files

Optional template rendering

API responses usually JSON

Integrate with frontend frameworks as needed

State Management

Stateless by default

Session management via secure cookies or JWT

Database-backed persistent state

In-memory caching for performance

Contextual state within handlers

Data Management

Parse JSON, form, and URL-encoded payloads

Connect to async or sync databases

Validate input manually or with libraries

Stream data for large responses

Log requests and responses

Architecture

Single-threaded event loop (IOLoop)

Non-blocking asynchronous request handling

Handler classes for routes

Supports both HTTP and TCP servers

Integration with third-party async libraries

Rendering Model

Client sends HTTP request -> Tornado IOLoop

RequestHandler or WebSocketHandler processes request

Async operations performed if needed

Response generated and sent back

IOLoop continues handling other connections

Architectural Patterns

Event-loop for non-blocking I/O

Handler-based routing

Async coroutines for concurrency

Modular extensions and utilities

WebSocket and streaming support

Real World Architectures

Real-time chat servers

Streaming dashboards

WebSocket-based APIs

IoT notification backends

High-concurrency microservices

Design Principles

Non-blocking, asynchronous I/O

Single-threaded event loop for high concurrency

Lightweight and modular framework

Flexible handler-based routing

Real-time and streaming-friendly design

Scalability Guide

Use multiple Tornado processes for horizontal scaling

Implement caching for high-traffic endpoints

Load balance with Nginx or HAProxy

Optimize IOLoop usage

Monitor and profile server performance

Migration Guide

Adapt from Flask/Django by replacing blocking handlers with async

Use RequestHandler/WebSocketHandler

Replace WSGI-specific middleware

Test async endpoints thoroughly

Monitor event loop for blocking operations

Performance Notes

Handles thousands of concurrent clients efficiently

Async I/O prevents blocking the main loop

Low latency for real-time connections

Efficient WebSocket and streaming support

Memory usage grows slowly under high load

Security Notes

Use HTTPS for secure communication

Sanitize inputs in handlers

Use secure cookies and authentication

Rate-limit or throttle connections if needed

Keep Tornado and dependencies updated

Monitoring Analytics

Log requests and responses

Track errors and exceptions

Monitor memory and CPU usage

Integrate with Prometheus, Grafana, or ELK

Profile event loop for bottlenecks

Code Quality

Follow Python best practices

Use async/await effectively

Write unit and integration tests

Document handlers and coroutines

Optimize IOLoop usage and performance

Practical Examples

Real-time chat server

Streaming stock price dashboard

Notification push service

Async CRUD API for IoT devices

Live collaboration platform backend

Troubleshooting

Ensure Python version supports asyncio

Check port availability

Handle uncaught exceptions in handlers

Monitor event loop for blocking operations

Use logging for debugging async tasks

Testing Guide

Use unittest or pytest for unit testing

Test async endpoints with `AsyncTestCase`

Mock async database calls

Validate WebSocket interactions

Automate tests with CI/CD

Deployment Options

Cloud services (AWS, GCP, Azure)

Docker containerization

Reverse proxy with Nginx for production

Gunicorn + Tornado for multiple processes

Systemd service or supervisor for process management

Tools Ecosystem

Python runtime

pip for package management

Postman/Insomnia for API testing

Async libraries like `aiomysql` or `motor`

Logging and monitoring tools (e.g., `logging` module)

Integrations

Databases (PostgreSQL, MongoDB, MySQL) via async drivers

WebSockets and long-polling

Caching with Redis or Memcached

Authentication and authorization modules

Frontend frameworks via JSON API

Productivity Tips

Use async handlers to avoid blocking

Compose small reusable handler classes

Monitor logs to detect slow operations

Automate tests and deployments

Integrate with async libraries for DB and caching

Challenges

Managing async coroutines efficiently

Avoiding blocking the event loop

Handling thousands of simultaneous connections

Integrating with async databases

Securing long-lived connections

Learning Path

Learn Python 3 basics

Understand async/await and coroutines

Create Tornado RequestHandler classes

Implement async APIs and WebSockets

Deploy high-concurrency Tornado apps

Skill Improvement Plan

Week 1: Python 3 and asyncio fundamentals

Week 2: Tornado basics and routing

Week 3: Async request handling and IOLoop

Week 4: WebSockets and streaming endpoints

Week 5: Deployment and performance tuning

Interview Questions

What is Tornado and why use it?

How does Tornado handle concurrency?

Explain IOLoop and asynchronous request handling

How to implement WebSockets in Tornado?

Compare Tornado with Flask or Django

Cheat Sheet

import tornado.web, tornado.ioloop -> import modules

class MainHandler(tornado.web.RequestHandler) -> define handler

async def get(self): -> async GET method

app = tornado.web.Application([...]) -> create app

app.listen(port); tornado.ioloop.IOLoop.current().start() -> start server

Books

Tornado Web Server

Python Asynchronous Programming with Tornado

Real-Time Web Apps with Tornado

High-Performance Python Web Development

Async Python and Tornado in Action

Tutorials

Getting started with Tornado

Build async REST APIs with Tornado

WebSocket server with Tornado

Streaming and long-polling examples

Deploy Tornado app to production

Official Docs

https://www.tornadoweb.org/

https://github.com/tornadoweb/tornado

Community Links

Tornado GitHub

Python Discord/Slack

StackOverflow Tornado questions

Reddit r/python

YouTube Tornado tutorials

Community Support

Tornado GitHub

Python Discord and Slack communities

StackOverflow Tornado questions

Reddit r/python

Official Tornado documentation

Monetization

Backend for SaaS real-time platforms

Live streaming and dashboards

IoT notification services

API-as-a-service solutions

Microservices for small-to-medium businesses

Future Roadmap

Enhanced asyncio integration

Better WebSocket and streaming support

Expanded async library compatibility

Improved documentation and examples

Focus on high-concurrency performance

When Not To Use

CPU-bound applications

Simple websites without concurrency needs

Projects needing a large ecosystem of pre-built modules

Teams unfamiliar with async programming

Applications requiring complex ORMs or admin panels

Final Summary

Tornado is an asynchronous Python web framework and networking library.

Designed for high-concurrency, real-time web services.

Supports HTTP, WebSockets, and streaming responses.

Flexible, lightweight, and event-loop-based architecture.

Ideal for APIs, chat servers, live dashboards, and IoT backends.

Faq

Is Tornado free?

Yes - open-source under the Apache 2.0 license.

Does Tornado support async/await?

Yes - supports Python's async/await syntax.

Is Tornado suitable for production?

Yes - especially for real-time and high-concurrency apps.

Does Tornado include WebSocket support?

Yes - built-in WebSocketHandler class.

Can Tornado scale horizontally?

Yes - with multiple processes and load balancers.

Code Sample Descriptions

1

Tornado Simple Counter API

import tornado.ioloop
import tornado.web

count = 0

class CounterHandler(tornado.web.RequestHandler):
    async def get(self):
        self.write({'count': count})

class IncrementHandler(tornado.web.RequestHandler):
    async def post(self):
        global count
        count += 1
        self.write({'count': count})

class DecrementHandler(tornado.web.RequestHandler):
    async def post(self):
        global count
        count -= 1
        self.write({'count': count})

class ResetHandler(tornado.web.RequestHandler):
    async def post(self):
        global count
        count = 0
        self.write({'count': count})

app = tornado.web.Application([
    (r'/counter', CounterHandler),
    (r'/counter/increment', IncrementHandler),
    (r'/counter/decrement', DecrementHandler),
    (r'/counter/reset', ResetHandler)
])

if __name__ == '__main__':
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Demonstrates a simple Tornado REST API with a counter using async handlers and in-memory state.

Let’s Try →
2

Tornado Hello World API

import tornado.ioloop
import tornado.web

class HelloHandler(tornado.web.RequestHandler):
    async def get(self):
        self.write({'message': 'Hello World'})

app = tornado.web.Application([
    (r'/', HelloHandler)
])

if __name__ == '__main__':
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

A minimal Tornado API returning Hello World.

Let’s Try →
3

Tornado JSON Echo

import tornado.ioloop
import tornado.web
import json

class EchoHandler(tornado.web.RequestHandler):
    async def post(self):
        data = json.loads(self.request.body)
        self.write(data)

app = tornado.web.Application([
    (r'/echo', EchoHandler)
])

if __name__ == '__main__':
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

A POST endpoint that echoes JSON data.

Let’s Try →
4

Tornado Query Parameter Example

import tornado.ioloop
import tornado.web

class GreetHandler(tornado.web.RequestHandler):
    async def get(self):
        name = self.get_argument('name', 'Guest')
        self.write({'message': f'Hello {name}'})

app = tornado.web.Application([
    (r'/greet', GreetHandler)
])

if __name__ == '__main__':
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Using query parameters to greet users.

Let’s Try →
5

Tornado Route Parameter Example

import tornado.ioloop
import tornado.web

class UserHandler(tornado.web.RequestHandler):
    async def get(self, user_id):
        self.write({'id': int(user_id), 'name': f'User {user_id}'})

app = tornado.web.Application([
    (r'/users/(\d+)', UserHandler)
])

if __name__ == '__main__':
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Returns user info based on URL parameter.

Let’s Try →
6

Tornado Middleware Logging

import tornado.ioloop
import tornado.web

class LogMiddleware(tornado.web.RequestHandler):
    async def prepare(self):
        print(f'{self.request.method} {self.request.uri}')

class IndexHandler(LogMiddleware):
    async def get(self):
        self.write({'message': 'Check console for logs'})

app = tornado.web.Application([
    (r'/', IndexHandler)
])

if __name__ == '__main__':
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Simple middleware to log requests in Tornado.

Let’s Try →
7

Tornado Async Delay Example

import tornado.ioloop
import tornado.web
import asyncio

class AsyncHandler(tornado.web.RequestHandler):
    async def get(self):
        await asyncio.sleep(1)
        self.write({'message': 'Async response'})

app = tornado.web.Application([
    (r'/async', AsyncHandler)
])

if __name__ == '__main__':
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

An async route returning data after a delay.

Let’s Try →
8

Tornado 404 Example

import tornado.ioloop
import tornado.web

class DefaultHandler(tornado.web.RequestHandler):
    def prepare(self):
        self.set_status(404)
        self.write({'error': 'Not Found'})

app = tornado.web.Application([], default_handler_class=DefaultHandler)

if __name__ == '__main__':
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Custom 404 error response.

Let’s Try →
9

Tornado Combined Routes Example

import tornado.ioloop
import tornado.web
import json

count = 0

class LogHandler(tornado.web.RequestHandler):
    async def prepare(self):
        print(f'{self.request.method} {self.request.uri}')

class EchoHandler(LogHandler):
    async def post(self):
        data = json.loads(self.request.body)
        self.write(data)

class CounterHandler(LogHandler):
    async def get(self):
        self.write({'count': count})
    async def post(self, action):
        global count
        if action == 'increment': count += 1
        elif action == 'decrement': count -= 1
        elif action == 'reset': count = 0
        self.write({'count': count})

app = tornado.web.Application([
    (r'/echo', EchoHandler),
    (r'/counter', CounterHandler),
    (r'/counter/(increment|decrement|reset)', CounterHandler)
])

if __name__ == '__main__':
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Logging, JSON echo, and counter in a single Tornado app.

Let’s Try →

Frequently Asked Questions about Tornado

What is Tornado?

Tornado is a Python web framework and asynchronous networking library, designed for handling thousands of simultaneous connections. It excels at real-time web services and long-lived network connections.

What are the primary use cases for Tornado?

Real-time chat applications. WebSocket-based dashboards. High-concurrency APIs and services. Long-polling or streaming data endpoints. IoT backends and notification services

What are the strengths of Tornado?

Handles large numbers of simultaneous connections efficiently. Real-time and streaming-friendly. Async/await syntax support. Lightweight and extensible. Good for low-latency applications

What are the limitations of Tornado?

Less suited for CPU-bound workloads. Smaller ecosystem compared to Django or Flask. Requires understanding of asynchronous programming. Manual setup for templating, authentication, and forms. Not ideal for simple static websites

How can I practice Tornado typing speed?

CodeSpeedTest offers 9+ real Tornado code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.