O documento discute a arquitetura de pipelines de dados, comparando as arquiteturas Lambda e Kappa. Apresenta qualidades essenciais de um bom pipeline de dados, como segurança, automação, monitoramento e testabilidade. Destaca também onde a linguagem Python é útil, incluindo ferramentas como PySpark, Pandas, Airflow e bibliotecas para testes e validação.
3. Agenda
Não é sobre Código, é sobre arquitetura
Anatomia de um produto de dados.
Lambda vs Kappa Architecture
Qualidades de um pipeline de dados.
Onde Python importa.
O objetivo é ajudar você a planejar excelentes produtos de dados baseados em Python.
4. Ingress Processes
Anatomia de um produto de dados.
Egress
DB
Logs
Jobs &
Datasets
DB
API’s
Volume / Variedade Veracidade / Velocidade Veracidade
Credits: Lars Albertsson https://www.youtube.com/watch?v=IVEl0bsTbdg
5. FUNCIONA EXAMENTE COMO UM SOFTWARE
Input Processes
RAM
Output
Files
Memory
Functions
Variables
Files
API’s
Credits: Lars Albertsson https://www.youtube.com/watch?v=IVEl0bsTbdg
8. Aplicações
Sistemas que precisam de dados armazenados permanentemente.
Query em dados imutáveis.
Sistemas que requerem grande volume de atualizações e produzem novos datasets constantemente.
Pros
Seguro e confiável.
Tolerante a falhas ( é possível reprocessar tudo do zero).
Escalável.
Todo histórico de dados é distribuído no Sistema de arquivos (
preferencialmente um Sistema de arquivos distribuídos).
Cons
Modelagem prematura leva a cenários de migração de schemas ou datasets
a dificuldades.
Exponencialmente caro enquanto o volume de dados cresce.
Cada ciclo de processamento se torna mais complexa.
O Código tende a se tornar complexa por causa da separação de
responsabilidades de cada camada da pipeline.
9. Kappa
Data
Speed Layer
Stream Real time views Query
Pro tip: Se seu objetivo não são resposta em tempo real, se mantenha na arquitetura
em Batch.
10. Aplicação
Sua arquitetura de ingestão de dados deve ter uma ordem de eventos bem definidas para que você possa interagir com o seu dataset a qualquer momento.
Sistemas ou Usuários que precisam de aprendizado em tempo real. ( Redes Sociais, Anúncios, Detecção de Fraudes ).
Foco em mudança continua de código.
Pros
Usa muito menos recursos que uma aplicação em Batch (lambda).
Ajuda os pipelines de Machine Learning a trabalhar próximo ao tempo real.
É horizontalmente escalável.
E você pode reprocessar seus dados apenas quando seus dados ou código
mudam.
Cons
Erros no processamento de dados exigem um excelente gerenciamento de
exceções e monitoramento.
Um bug pode parar o pipeline de dados completamente.
12. Segurança
Níveis de acesso
ao dados
Camadas de
privacidade
Formatos de
arquivos comuns
Separação de
Responsabilidades
Evitar duplicação
de código e hard-
coding.
14. Monitoramento
Deixe os produtos na
cloud ajudarem nisso. É
barato e efetivo.
Evite vendor
lock-in.
Monitoramento
da
Infraestrutura
15. Testável e
Rastreável.
TESTES DE REGRESSÃO ENTRADAS
DETERMINÍSTICAS
ASSIM COMO SAÍDAS.
FOCO EM TESTES DE
UNIDADE E
INTEGRAÇÃO.
TESTE DE TODOS OS
COMPONENTES
EXTERNOS.
CRIAÇÃO DE TESTES
END-TO-END
17. Onde Python
resolve :)
PySpark - Apache Spark Python API.
dask - Uma biblioteca de computação paralela flexível para
computação analítica.
luigi - Um módulo que ajuda você a construir pipelines
complexos para arquiteturas em batch.
• ELT
• Streaming
• Analysis
• Management & Scheduling
• Testing
• Validation
18. Onde Python
resolve :)
faust - Uma biblioteca de processamento de stream
portando as ideias de Kafka Streams para Python.
streamparse - Executa o código Python contra stream de
dados em tempo real via Apache Storm.
• ELT
• Streaming
• Analysis
• Management & Scheduling
• Testing
• Validation
19. Onde Python
resolve :)
Pandas - Uma biblioteca que fornece estruturas de dados e
ferramentas de análise de dados de alto desempenho e
fácil de usar.
Blaze - interface para trabalhar com Big Data com NumPy e
Pandas.
Optimus - Agile Data Science Workflows para trabalho com
PySpark.
• ELT
• Streaming
• Analysis
• Management & Scheduling
• Testing
• Validation
20. Onde Python
resolve :)
Airflow - Airflow é a Plataforma de gerencialmento de
trabalho de pipeline de dados programável.
• ELT
• Streaming
• Analysis
• Management & Scheduling
• Testing
• Validation
21. Onde Python
resolve :)
pytest - Uma ferramenta de teste Python completa
madura.
mimesis - é uma biblioteca Python que ajuda você a gerar
dados falsos.
fake2db - Geração de banco de dados temporários.
https://github.com/holdenk/spark-testing-base - Um
framework para implementar testes em pyspark.
• ELT
• Streaming
• Analysis
• Management & Scheduling
• Testing
• Validation
22. Onde Python
resolve :)
Cerberus - Uma biblioteca de validação de dados leve e
extensível.
schema - Uma biblioteca para validar estruturas de dados
Python.
voluptuous - Uma biblioteca de validação de dados Python.
• ELT
• Streaming
• Analysis
• Management & Scheduling
• Testing
• Validation
Thank you, the organization, to invite me and make it possible online in this hard times!
Since it’s my first time on the way to talk, I would like to propose, fell free to drop a message any time on the channel, I can follow in real time and awnser!
We can create this dynamic.
Falar sobre mim
16 anos de carreira
Aprendi a programar com python
Transicionei entre outras tecnologias por causa do mercado
Ja organizei conferencias
Envolvido com a comunidades
Feedback no telegram ou twitter
Atualmente na GitHub
My goal is to share i've learned and help you to start to planning great data driven products. I failled a lot of times, community helped.
Its not to talk about code or python code, is about talking abour data and how python is a key stone.
The beginning of the software development are the same, whats change is how your apply it in the data scenario.
I took all necessary procedures, but something wrong can happened.
Para aqueles que estao começando, sao insights para ser mais efetivo.
Let’s understand the anatomy of a data pipeline
1) In the anatomy, you have thing generating data all the time in the left. Today anything generates data today! Telemetry, logs, databases.
It’s called ingress!
2) The concept of big data is not about the amount! Is about volume!
The theory of Big Data is represented by 5 v’s
In the ingress we can represent the idea of the two first v’s
Volume: Quantity of data you are storing?
Variety: Type of Data? Traditional data types (structured data) ? unstructured data, which is where things like Twitter feeds, audio files, MRI images, web pages, web logs
This is stored on a thing called datalake! Yes, it’s like a big place where you put everything it!
ELT
Eventually you need to create processes or pipelines to processes it and send the data to egress part: here we have more 2 v’s
Veracity: refers to the trustworthiness of the data. Can the manager rely on the fact that the data is representative?
Velocity: Velocity is the frequency of incoming data that needs to be processed. Imagine a bank needing to process the payment and fraud detections.
Egress
Value: Seems obvious, but does the data is bringing value? Are you able to discovery an issue or a valuable insight?
It’s exactly a computer program, where you have an input and processes and a output.
Voce tem usuarios manipulando arquivos, interagindo com UI's e varias funcoes manipulando esses inputs!
no fim o que voce quer é um arquivo final ou lagum tipo de resultado que seja consumivel pelo usuario, como uma mensagem, and UI or etc.
ok, agora vamos falar sobre os tipos de arquitetura que sao well - accepted no mercado.
Não sao diferentes, mas sim complementares. É muito importante entender a diferença entre eles
e o tipo de uso, porque é o que vai determinar o qual simples and evolutiva será sua arquitetura.
It’s a architectural model that was thought to deal with a huge volume of data in a efficient way. You have two premises here:
1) Reduce the latency, or the time to processes the data
high throughput -> low latency -> near-real-time application
2) Any change in the data state, starts a new event to the system or process. Its called Event Sourcing:
Event Sourcing
It’s the concept of using events to make predictions and storing changes in a system in a real time basis, ensures that all changes to application state are stored as a sequence of events.
For example, a interaction on a product or a bank transaction might change the state of the data ( card blocked due to fraud, or enrich a data due a interaction on a web page)
Let’s talk about the layers
Batch layer
Consumes the coming from the data system, simultaneously with the speed layers:
Any new data / event that comes is processes on top of the data lake.
Data lake is base of the layer. ( Generating ML Models, extract datasets, raw data)
Speed Layer:
Speed layers, uses the results of the batch layer ( or event sourcing ), because the data processed in the batch layer will generate a new delta or results ( ML models, or Datasets ).
Here is the most important, the speed layer outputs the enriched data to support the serving layer to reduce latency of the queries.
Speed Layer deals just with the near real time data.
Serving Layer
The serving layer serves the data from both layers:
Batch layers as views of the data ingress
Speed Layer near real time views with enriched data
Kappa is not a replacement for Lambda architecture but an alternative to provide performance in some scenarios that lambda and batch layer is no necessary.
It is used to process stream data, perfom real-time process, especially for analytics and a single stack ( maily in a code base)
It’s might be considered as a simplified version of the speed layer.
You can delivery new features, change the code, fixing bugs, and deploy easely, because you do need to back the data.
https://www.knowledgehut.com/blog/cloud-computing/what-is-data-pipeline
How can access the data lake? How can access the processes and sensitive data ?
What will be served on the Egress?
How can change the code of the pipeline? Is there a formal processes?
The security comes from the code as well!
como um pipeline é um codigo,
apicar versionamento
usar a ferramenta certa para o problema a ser resolvido é essencial: python é um bom integrador
é por isso que nao estamos falando necessariamente de codigo python aqui, mas sim como python is a key stone in a pipeline.
seu CI deve conter todas as ferramentas basicas possiveis, como code review e o lint para garantir um codigo estaticamente saudavel e formatado.
Deploy a monitoring platform is quite easy but it's expensive to maintain and scale
so, prefer delegate it to cloud based logs, but try to avoid vendor lock-in.
Implementar testes de regreção para todos os componentes de codigo do pipeline é essencial.
Como?
Your inputs always must be deterministic, it means you must now the schema and possible the types
Cover with unit tests, all aspects.
Containerize third party components and create integration tests.
Implement end to end tests in a staging env, (it's not expensive , se voce estiver usando fornecedores na cloud,
voce pode simplemente replicar seus deploys para um novo ambiente).