Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Capabilities and Sessions

Session Lifecycle and Timeouts

Follow an Appium session from creation to deletion, learn which timeouts end it, how to restart apps without a new session, and how to avoid leaked sessions.

A session is the long conversation between your test and one device. It begins when you create the driver and ends when you call quit (or the server gives up). Everything that happens in between, finding elements, tapping, reading text, belongs to that session. Managing sessions well is how you keep tests isolated, fast and free of leaks.

This lesson covers the lifecycle, the timeouts that can end or delay a session, app-level operations inside a session, and strategies for how many sessions to create.

The lifecycle

stateDiagram-v2
  [*] --> Creating: POST /session
  Creating --> Active: device ready, app launched
  Creating --> Failed: bad capabilities or device error
  Active --> Active: commands (find, click, ...)
  Active --> Expired: no commands for newCommandTimeout
  Active --> Closed: DELETE /session (quit)
  Expired --> [*]
  Closed --> [*]
  Failed --> [*]

Figure: the states of a session. Only Active accepts commands.

  1. Creating. The server validates capabilities, picks a driver, prepares the device, installs and launches the app. This is the slowest phase, often 5 to 60 seconds.
  2. Active. Commands run one at a time. Most drivers process one command per session at a time.
  3. Ending. quit() deletes the session; the driver stops its helper, may uninstall things according to reset settings and frees the device.

If the client forgets to quit, the server eventually ends the session by itself, but the device may stay busy until then.

Timeouts that matter

Timeout Where What it does
appium:newCommandTimeout capability Seconds without any client command before the server ends the session (default 60). Set 0 to disable, but then leaked sessions never expire.
Session creation timeout client How long the client waits for POST /session. Cloud devices need more.
HTTP read timeout client How long the client waits for a single command's response.
Implicit wait session How long find_element retries before failing.
Driver-specific timeouts capabilities/settings Server launch, WDA launch, idle waiting.

A typical surprise: you set a breakpoint in your IDE, debug for two minutes, then continue and the next command returns "session not found" or "terminated due to inactivity". The server expired the session while you were thinking. Raise newCommandTimeout when debugging.

Operations inside a session

Many things do not need a new session.

Python
# Read-only: common session-level commands in the Python client
driver.background_app(5)            # send app to background for 5 s, then bring back
driver.terminate_app("com.example.shop")
driver.activate_app("com.example.shop")
driver.install_app("/builds/shop-debug.apk")
print(driver.query_app_state("com.example.shop"))
driver.reset()                      # deprecated in recent versions: prefer terminate and activate
driver.orientation = "LANDSCAPE"
driver.get_screenshot_as_file("screen.png")
print(driver.page_source[:200])

(The names of some helpers vary slightly between client versions; check the client's documentation. The idea is stable: terminate and activate restart the app inside the same session, which is much faster than creating a new session.)

One session per test, per class, or per run?

Strategy Speed Isolation Notes
New session per test Slowest Best Start clean each time; easiest to reason about
One session per test class/file Medium Good if you restart the app between tests Common compromise
One session per run Fastest Weakest State leaks; one crash breaks everything

A balanced approach is one session per test class, with terminate_app plus activate_app (or noReset with explicit state setup) between tests. For parallel runs, each worker needs its own session and its own device.

Always clean up

Put session creation in a fixture and cleanup in its teardown:

Python
import pytest

@pytest.fixture
def driver():
    drv = webdriver.Remote("http://127.0.0.1:4723", options=make_options())
    yield drv
    drv.quit()

Teardown runs even when the test fails, which keeps the device free for the next test.

Model a session in a stand-in

This stand-in is a session manager with a simulated clock. It shows creation, commands that refresh the idle timer, expiry after newCommandTimeout, and what happens to a command sent to an expired session. Time is simulated by a counter, so output is deterministic.

JS Stand-in: sessions and newCommandTimeout

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Restart the app without a new session

The second stand-in compares the cost of three strategies for a suite. The seconds are illustrative round numbers (real values depend on device and app), but the shape of the result, a new session per test costs most, is accurate.

JS Stand-in: cost of session strategies

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The cheapest option is rarely the best one: weigh the saved minutes against flakiness from leaked state.

Common lifecycle errors

  • "A session is either terminated or not started": the session expired, crashed or was already quit. Look earlier in the log for why.
  • Device stays busy: a previous run did not quit. Kill stale sessions or restart the server and adb.
  • Intermittent first-test failure: creation raced with a slow emulator boot; wait for sys.boot_completed or raise creation timeouts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does newCommandTimeout control?

    If the client sends no command for this long, the server expires the session.
  2. 2. You paused in a debugger for two minutes and the next command failed with a terminated session. Why?

    Raise newCommandTimeout while debugging, or the idle timer will end the session.
  3. 3. Which approach restarts the app fastest while keeping the session?

    Terminating and activating the app is quick and avoids session creation cost.
  4. 4. Where should quit() live in a test suite?

    Teardown code runs on failure too, so the device is always released.

Summary

  • A session goes through creating, active and ended states; creation is the slow part.
  • newCommandTimeout ends idle sessions; raise it when debugging.
  • Use app-level commands (terminate_app, activate_app) to restart the app inside a session.
  • Choose per test, per class or per run on the balance of speed and isolation.
  • Always release the session in a fixture or teardown.

Next: Server Arguments and Config Files